Open History to see the last commit
1import { MutationObserver } from '@tanstack/query-core'
2import { createValueAccessor, readAccessor } from './accessor.js'
3import { createMissingQueryClientError } from './context.js'
4import { BaseController } from './controllers/BaseController.js'
5import type { Accessor, ValueAccessor } from './accessor.js'
6import type {
7 DefaultError,
8 MutateFunction,
9 MutationObserverOptions,
10 MutationObserverResult,
11 QueryClient,
12} from '@tanstack/query-core'
13import type { ReactiveControllerHost } from 'lit'
14β
15/**
16 * Options accepted by `createMutationController`.
17 *
18 * This is the Lit adapter shape for `MutationObserverOptions`. Pass it directly
19 * or through an `Accessor` when the options depend on Lit host state.
20 */
21export type CreateMutationOptions<
22 TData = unknown,
23 TError = DefaultError,
24 TVariables = void,
25 TOnMutateResult = unknown,
26> = MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
27β
28/**
29 * Accessor returned by `createMutationController`.
30 *
31 * Call the accessor or read its `current` property to get the latest mutation
32 * result. The attached methods delegate to the active mutation observer.
33 */
34export type MutationResultAccessor<TData, TError, TVariables, TOnMutateResult> =
35 ValueAccessor<
36 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
37 > & {
38 /**
39 * Starts the mutation and swallows the returned promise.
40 *
41 * Throws synchronously if no `QueryClient` can be resolved.
42 */
43 mutate: (
44 ...args: Parameters<
45 MutateFunction<TData, TError, TVariables, TOnMutateResult>
46 >
47 ) => void
48 /**
49 * Starts the mutation and returns the observer promise.
50 *
51 * Rejects if no `QueryClient` can be resolved.
52 */
53 mutateAsync: MutationObserverResult<
54 TData,
55 TError,
56 TVariables,
57 TOnMutateResult
58 >['mutate']
59 /** Resets the mutation observer to its idle state. */
60 reset: MutationObserverResult<
61 TData,
62 TError,
63 TVariables,
64 TOnMutateResult
65 >['reset']
66 /** Removes the controller from its Lit host and unsubscribes observers. */
67 destroy: () => void
68 }
69β
70/**
71 * Returns the result used while no `QueryClient` is available: `'idle'`, with a `mutate` that
72 * rejects with the missing client error.
73 * @returns A new result object in that state.
74 */
75function createIdleMutationResult<
76 TData,
77 TError,
78 TVariables,
79 TOnMutateResult,
80>(): MutationObserverResult<TData, TError, TVariables, TOnMutateResult> {
81 return {
82 context: undefined,
83 data: undefined,
84 error: null,
85 failureCount: 0,
86 failureReason: null,
87 isError: false,
88 isIdle: true,
89 isPending: false,
90 isPaused: false,
91 isSuccess: false,
92 status: 'idle',
93 submittedAt: 0,
94 variables: undefined,
95 mutate: () => Promise.reject(createMissingQueryClientError()),
96 reset: () => undefined,
97 }
98}
99β
100class MutationController<
101 TData,
102 TError,
103 TVariables,
104 TOnMutateResult,
105> extends BaseController<
106 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
107> {
108 private readonly options: Accessor<
109 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
110 >
111 private observer:
112 MutationObserver<TData, TError, TVariables, TOnMutateResult> | undefined
113 private unsubscribe: (() => void) | undefined
114 private queryClient: QueryClient | undefined
115β
116 constructor(
117 host: ReactiveControllerHost,
118 options: Accessor<
119 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
120 >,
121 queryClient?: QueryClient,
122 ) {
123 super(host, createIdleMutationResult(), queryClient)
124 this.options = options
125β
126 if (!queryClient) {
127 return
128 }
129β
130 if (typeof options === 'function') {
131 return
132 }
133β
134 const observer = new MutationObserver(
135 queryClient,
136 this.defaultOptions(queryClient),
137 )
138 this.queryClient = queryClient
139 this.observer = observer
140 this.result = observer.getCurrentResult()
141 }
142β
143 protected override onConnected(): void {
144 if (!this.syncClient()) {
145 return
146 }
147β
148 this.refreshOptions()
149 this.subscribe()
150 if (this.observer) {
151 this.setResult(this.observer.getCurrentResult())
152 }
153 }
154β
155 protected override onDisconnected(): void {
156 this.unsubscribeObserver()
157 this.syncClient()
158 }
159β
160 protected override onHostUpdate(): void {
161 if (typeof this.options !== 'function') {
162 return
163 }
164β
165 this.refreshOptions()
166 }
167β
168 protected override onQueryClientChanged(): void {
169 if (!this.syncClient() || !this.connectedState) {
170 return
171 }
172β
173 this.refreshOptions()
174 this.subscribe()
175 if (this.observer) {
176 this.setResult(this.observer.getCurrentResult())
177 }
178 }
179β
180 mutate = (
181 ...args: Parameters<
182 MutateFunction<TData, TError, TVariables, TOnMutateResult>
183 >
184 ): void => {
185 if (!this.syncClient() || !this.observer) {
186 throw createMissingQueryClientError()
187 }
188β
189 void this.observer.mutate(args[0] as TVariables, args[1]).catch(() => {
190 // Intentionally swallow in sync mutate path.
191 })
192 }
193β
194 mutateAsync: MutationObserverResult<
195 TData,
196 TError,
197 TVariables,
198 TOnMutateResult
199 >['mutate'] = (...args) => {
200 if (!this.syncClient() || !this.observer) {
201 return Promise.reject(createMissingQueryClientError())
202 }
203β
204 return this.observer.mutate(args[0] as TVariables, args[1])
205 }
206β
207 reset: MutationObserverResult<
208 TData,
209 TError,
210 TVariables,
211 TOnMutateResult
212 >['reset'] = () => {
213 if (!this.syncClient() || !this.observer) {
214 return
215 }
216β
217 this.observer.reset()
218 this.setResult(this.observer.getCurrentResult())
219 }
220β
221 private subscribe(): void {
222 if (!this.observer) {
223 return
224 }
225β
226 if (this.unsubscribe) {
227 return
228 }
229β
230 this.unsubscribe = this.observer.subscribe((next) => {
231 this.setResult(next)
232 })
233 }
234β
235 private unsubscribeObserver(): void {
236 this.unsubscribe?.()
237 this.unsubscribe = undefined
238 }
239β
240 private syncClient(): boolean {
241 const nextClient = this.tryGetQueryClient()
242 if (!nextClient) {
243 this.unsubscribeObserver()
244 this.queryClient = undefined
245 this.observer = undefined
246 this.setResult(createIdleMutationResult())
247 return false
248 }
249β
250 if (nextClient === this.queryClient) {
251 return true
252 }
253β
254 this.unsubscribeObserver()
255 this.queryClient = nextClient
256 this.observer = new MutationObserver(
257 this.queryClient,
258 this.defaultOptions(this.queryClient),
259 )
260 this.setResult(this.observer.getCurrentResult())
261 return true
262 }
263β
264 private refreshOptions(): boolean {
265 if (!this.syncClient() || !this.observer || !this.queryClient) {
266 return false
267 }
268β
269 this.observer.setOptions(this.defaultOptions())
270 this.setResult(this.observer.getCurrentResult())
271 return true
272 }
273β
274 private defaultOptions(
275 client = this.queryClient,
276 ): MutationObserverOptions<TData, TError, TVariables, TOnMutateResult> {
277 if (!client) {
278 throw createMissingQueryClientError()
279 }
280β
281 return client.defaultMutationOptions(readAccessor(this.options))
282 }
283}
284β
285/**
286 * Creates a Lit reactive controller that subscribes the host to a mutation.
287 *
288 * The returned accessor is callable and also exposes `current`, `mutate`,
289 * `mutateAsync`, `reset`, and `destroy`. When `options` is a function, it is
290 * re-read during host updates so mutation options can follow reactive host
291 * state.
292 *
293 * If `queryClient` is omitted, the controller resolves the client from the
294 * nearest connected `QueryClientProvider`.
295 * @param host - The Lit reactive controller host that owns the mutation
296 * subscription.
297 * @param options - Mutation observer options, or a getter that returns options.
298 * @param queryClient - Optional explicit query client. Provide this for
299 * controllers that should not resolve a client from Lit context.
300 * @returns An accessor for the latest mutation result with mutation helper
301 * methods.
302 * @example
303 * ```ts
304 * import { LitElement, html } from 'lit'
305 * import { createMutationController } from '@tanstack/lit-query'
306 *
307 * class AddTodoForm extends LitElement {
308 * private readonly addTodo = createMutationController(this, {
309 * mutationFn: (title: string) =>
310 * fetch('/api/todos', { method: 'POST', body: JSON.stringify({ title }) }),
311 * })
312 *
313 * render() {
314 * const mutation = this.addTodo()
315 *
316 * return html`
317 * <button ?disabled=${mutation.isPending} @click=${() => this.addTodo.mutate('Ship docs')}>
318 * Add todo
319 * </button>
320 * `
321 * }
322 * }
323 * ```
324 */
325export function createMutationController<
326 TData = unknown,
327 TError = DefaultError,
328 TVariables = void,
329 TOnMutateResult = unknown,
330>(
331 host: ReactiveControllerHost,
332 options: Accessor<
333 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
334 >,
335 queryClient?: QueryClient,
336): MutationResultAccessor<TData, TError, TVariables, TOnMutateResult> {
337 const controller = new MutationController(host, options, queryClient)
338β
339 return Object.assign(
340 createValueAccessor(() => controller.current),
341 {
342 mutate: controller.mutate,
343 mutateAsync: controller.mutateAsync,
344 reset: controller.reset,
345 destroy: () => controller.destroy(),
346 },
347 )
348}