Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

createMutationController.ts

345 lines8.8 KB

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