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
72 * `mutate` that rejects with the missing client error.
73 *
74 * @returns A new result object in that state.
75 */
76function createIdleMutationResult<
77 TData,
78 TError,
79 TVariables,
80 TOnMutateResult,
81>(): MutationObserverResult<TData, TError, TVariables, TOnMutateResult> {
82 return {
83 context: undefined,
84 data: undefined,
85 error: null,
86 failureCount: 0,
87 failureReason: null,
88 isError: false,
89 isIdle: true,
90 isPending: false,
91 isPaused: false,
92 isSuccess: false,
93 status: 'idle',
94 submittedAt: 0,
95 variables: undefined,
96 mutate: () => Promise.reject(createMissingQueryClientError()),
97 reset: () => undefined,
98 }
99}
100β
101class MutationController<
102 TData,
103 TError,
104 TVariables,
105 TOnMutateResult,
106> extends BaseController<
107 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
108> {
109 private readonly options: Accessor<
110 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
111 >
112 private observer:
113 | MutationObserver<TData, TError, TVariables, TOnMutateResult>
114 | undefined
115 private unsubscribe: (() => void) | undefined
116 private queryClient: QueryClient | undefined
117β
118 constructor(
119 host: ReactiveControllerHost,
120 options: Accessor<
121 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
122 >,
123 queryClient?: QueryClient,
124 ) {
125 super(host, createIdleMutationResult(), queryClient)
126 this.options = options
127β
128 if (!queryClient) {
129 return
130 }
131β
132 if (typeof options === 'function') {
133 return
134 }
135β
136 const observer = new MutationObserver(
137 queryClient,
138 this.defaultOptions(queryClient),
139 )
140 this.queryClient = queryClient
141 this.observer = observer
142 this.result = observer.getCurrentResult()
143 }
144β
145 protected override onConnected(): void {
146 if (!this.syncClient()) {
147 return
148 }
149β
150 this.refreshOptions()
151 this.subscribe()
152 if (this.observer) {
153 this.setResult(this.observer.getCurrentResult())
154 }
155 }
156β
157 protected override onDisconnected(): void {
158 this.unsubscribeObserver()
159 this.syncClient()
160 }
161β
162 protected override onHostUpdate(): void {
163 if (typeof this.options !== 'function') {
164 return
165 }
166β
167 this.refreshOptions()
168 }
169β
170 protected override onQueryClientChanged(): void {
171 if (!this.syncClient() || !this.connectedState) {
172 return
173 }
174β
175 this.refreshOptions()
176 this.subscribe()
177 if (this.observer) {
178 this.setResult(this.observer.getCurrentResult())
179 }
180 }
181β
182 mutate = (
183 ...args: Parameters<
184 MutateFunction<TData, TError, TVariables, TOnMutateResult>
185 >
186 ): void => {
187 if (!this.syncClient() || !this.observer) {
188 throw createMissingQueryClientError()
189 }
190β
191 void this.observer.mutate(args[0] as TVariables, args[1]).catch(() => {
192 // Intentionally swallow in sync mutate path.
193 })
194 }
195β
196 mutateAsync: MutationObserverResult<
197 TData,
198 TError,
199 TVariables,
200 TOnMutateResult
201 >['mutate'] = (...args) => {
202 if (!this.syncClient() || !this.observer) {
203 return Promise.reject(createMissingQueryClientError())
204 }
205β
206 return this.observer.mutate(args[0] as TVariables, args[1])
207 }
208β
209 reset: MutationObserverResult<
210 TData,
211 TError,
212 TVariables,
213 TOnMutateResult
214 >['reset'] = () => {
215 if (!this.syncClient() || !this.observer) {
216 return
217 }
218β
219 this.observer.reset()
220 this.setResult(this.observer.getCurrentResult())
221 }
222β
223 private subscribe(): void {
224 if (!this.observer) {
225 return
226 }
227β
228 if (this.unsubscribe) {
229 return
230 }
231β
232 this.unsubscribe = this.observer.subscribe((next) => {
233 this.setResult(next)
234 })
235 }
236β
237 private unsubscribeObserver(): void {
238 this.unsubscribe?.()
239 this.unsubscribe = undefined
240 }
241β
242 private syncClient(): boolean {
243 const nextClient = this.tryGetQueryClient()
244 if (!nextClient) {
245 this.unsubscribeObserver()
246 this.queryClient = undefined
247 this.observer = undefined
248 this.setResult(createIdleMutationResult())
249 return false
250 }
251β
252 if (nextClient === this.queryClient) {
253 return true
254 }
255β
256 this.unsubscribeObserver()
257 this.queryClient = nextClient
258 this.observer = new MutationObserver(
259 this.queryClient,
260 this.defaultOptions(this.queryClient),
261 )
262 this.setResult(this.observer.getCurrentResult())
263 return true
264 }
265β
266 private refreshOptions(): boolean {
267 if (!this.syncClient() || !this.observer || !this.queryClient) {
268 return false
269 }
270β
271 this.observer.setOptions(this.defaultOptions())
272 this.setResult(this.observer.getCurrentResult())
273 return true
274 }
275β
276 private defaultOptions(
277 client = this.queryClient,
278 ): MutationObserverOptions<TData, TError, TVariables, TOnMutateResult> {
279 if (!client) {
280 throw createMissingQueryClientError()
281 }
282β
283 return client.defaultMutationOptions(readAccessor(this.options))
284 }
285}
286β
287/**
288 * Creates a Lit reactive controller that subscribes the host to a mutation.
289 *
290 * The returned accessor is callable and also exposes `current`, `mutate`,
291 * `mutateAsync`, `reset`, and `destroy`. When `options` is a function, it is
292 * re-read during host updates so mutation options can follow reactive host
293 * state.
294 *
295 * If `queryClient` is omitted, the controller resolves the client from the
296 * nearest connected `QueryClientProvider`.
297 *
298 * @example
299 * ```ts
300 * import { LitElement, html } from 'lit'
301 * import { createMutationController } from '@tanstack/lit-query'
302 *
303 * class AddTodoForm extends LitElement {
304 * private readonly addTodo = createMutationController(this, {
305 * mutationFn: (title: string) =>
306 * fetch('/api/todos', {
307 * method: 'POST',
308 * body: JSON.stringify({ title }),
309 * }),
310 * })
311 *
312 * render() {
313 * const mutation = this.addTodo()
314 *
315 * return html`
316 * <button
317 * ?disabled=${mutation.isPending}
318 * @click=${() => this.addTodo.mutate('Ship docs')}
319 * >
320 * Add todo
321 * </button>
322 * `
323 * }
324 * }
325 * ```
326 *
327 * @param host - The Lit reactive controller host that owns the mutation
328 * subscription.
329 * @param options - Mutation observer options, or a getter that returns options.
330 * @param queryClient - Optional explicit query client. Provide this for
331 * controllers that should not resolve a client from Lit context.
332 * @returns An accessor for the latest mutation result with mutation helper
333 * methods.
334 */
335export function createMutationController<
336 TData = unknown,
337 TError = DefaultError,
338 TVariables = void,
339 TOnMutateResult = unknown,
340>(
341 host: ReactiveControllerHost,
342 options: Accessor<
343 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
344 >,
345 queryClient?: QueryClient,
346): MutationResultAccessor<TData, TError, TVariables, TOnMutateResult> {
347 const controller = new MutationController(host, options, queryClient)
348β
349 return Object.assign(
350 createValueAccessor(() => controller.current),
351 {
352 mutate: controller.mutate,
353 mutateAsync: controller.mutateAsync,
354 reset: controller.reset,
355 destroy: () => controller.destroy(),
356 },
357 )
358}