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

mutation.ts

560 lines15.9 KB

1import { notifyManager } from './notifyManager'
2import { Removable } from './removable'
3import { createRetryer } from './retryer'
4import type {
5 DefaultError,
6 MutationFunctionContext,
7 MutationMeta,
8 MutationOptions,
9 MutationStatus,
10} from './types'
11import type { MutationCache } from './mutationCache'
12import type { MutationObserver } from './mutationObserver'
13import type { Retryer } from './retryer'
14import type { QueryClient } from './queryClient'
15​
16// TYPES
17​
18interface MutationConfig<TData, TError, TVariables, TOnMutateResult> {
19 client: QueryClient
20 mutationId: number
21 mutationCache: MutationCache
22 options: MutationOptions<TData, TError, TVariables, TOnMutateResult>
23 state?: MutationState<TData, TError, TVariables, TOnMutateResult>
25​
26/**
27 * The raw state stored on a `Mutation` instance. This is the underlying state
28 * that observer results (e.g. `MutationObserverResult`) are derived from.
29 */
30export interface MutationState<
31 TData = unknown,
32 TError = DefaultError,
33 TVariables = unknown,
34 TOnMutateResult = unknown,
35> {
36 /**
37 * The value returned by `onMutate`, if defined. Passed to `onSuccess`,
38 * `onError` and `onSettled` as the mutation's context.
39 */
40 context: TOnMutateResult | undefined
41 /**
42 * The last successfully resolved data for the mutation.
43 */
44 data: TData | undefined
45 /**
46 * The error object for the mutation, if the last attempt resulted in an error.
47 * - Defaults to `null`.
48 */
49 error: TError | null
50 /**
51 * The number of times the mutation function has failed for the current attempt.
52 */
53 failureCount: number
54 /**
55 * The reason the current attempt failed, as reported by the retryer.
56 */
57 failureReason: TError | null
58 /**
59 * Whether the mutation is currently paused (see network mode), or is
60 * waiting for another mutation with the same `scope` to finish.
61 */
62 isPaused: boolean
63 /**
64 * The status of the mutation.
65 */
66 status: MutationStatus
67 /**
68 * The variables the mutation was last called with.
69 */
70 variables: TVariables | undefined
71 /**
72 * The timestamp for when the mutation was submitted.
73 */
74 submittedAt: number
76​
77interface FailedAction<TError> {
78 type: 'failed'
79 failureCount: number
80 error: TError | null
82​
83interface PendingAction<TVariables, TOnMutateResult> {
84 type: 'pending'
85 isPaused: boolean
86 variables?: TVariables
87 context?: TOnMutateResult
89​
90interface SuccessAction<TData> {
91 type: 'success'
92 data: TData
94​
95interface ErrorAction<TError> {
96 type: 'error'
97 error: TError
99​
100interface PauseAction {
101 type: 'pause'
103​
104interface ContinueAction {
105 type: 'continue'
107​
108/**
109 * The actions a mutation dispatches to update its state, e.g. when it starts, fails, pauses, or
110 * succeeds.
111 */
112export type Action<TData, TError, TVariables, TOnMutateResult> =
113 | ContinueAction
114 | ErrorAction<TError>
115 | FailedAction<TError>
116 | PendingAction<TVariables, TOnMutateResult>
117 | PauseAction
118 | SuccessAction<TData>
119​
120// CLASS
121​
122/**
123 * Represents a single mutation attempt. A `Mutation` holds the mutation's
124 * options, state (data/error/status), and the `MutationObserver`s currently
125 * subscribed to it.
126 *
127 * Instances are created and managed internally by `MutationCache`; application
128 * code typically interacts with mutations indirectly through `QueryClient` or
129 * a framework hook like `useMutation`. Direct access to a `Mutation` instance
130 * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
131 * @example
132 * ```ts
133 * const mutationCache = queryClient.getMutationCache()
134 *
135 * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
136 * ```
137 */
138export class Mutation<
139 TData = unknown,
140 TError = DefaultError,
141 TVariables = unknown,
142 TOnMutateResult = unknown,
143> extends Removable {
144 state: MutationState<TData, TError, TVariables, TOnMutateResult>
145 options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>
146 readonly mutationId: number
147​
148 #client: QueryClient
149 #observers: Array<
150 MutationObserver<TData, TError, TVariables, TOnMutateResult>
151 >
152 #mutationCache: MutationCache
153 #retryer?: Retryer<TData>
154​
155 constructor(
156 config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,
157 ) {
158 super()
159​
160 this.#client = config.client
161 this.mutationId = config.mutationId
162 this.#mutationCache = config.mutationCache
163 this.#observers = []
164 this.state = config.state || getDefaultState()
165​
166 this.setOptions(config.options)
167 this.scheduleGc()
168 }
169​
170 /**
171 * Replaces the mutation's options and applies their `gcTime`.
172 * @internal
173 * @param options - The new mutation options.
174 */
175 setOptions(
176 options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,
177 ): void {
178 this.options = options
179​
180 this.updateGcTime(this.options.gcTime)
181 }
182​
183 /**
184 * The `meta` object passed in the mutation's options, if any.
185 * @returns The mutation's `meta`, or `undefined` if none was set.
186 */
187 get meta(): MutationMeta | undefined {
188 return this.options.meta
189 }
190​
191 /**
192 * Subscribes an observer to the mutation and stops its garbage collection.
193 * @internal
194 * @param observer - The observer to add. Adding an observer that is already subscribed does
195 * nothing.
196 */
197 addObserver(observer: MutationObserver<any, any, any, any>): void {
198 if (!this.#observers.includes(observer)) {
199 this.#observers.push(observer)
200​
201 // Stop the mutation from being garbage collected
202 this.clearGcTimeout()
203​
204 this.#mutationCache.notify({
205 type: 'observerAdded',
206 mutation: this,
207 observer,
208 })
209 }
210 }
211​
212 /**
213 * Unsubscribes an observer from the mutation.
214 * @internal
215 * @param observer - The observer to remove. Garbage collection is scheduled afterwards.
216 */
217 removeObserver(observer: MutationObserver<any, any, any, any>): void {
218 this.#observers = this.#observers.filter((x) => x !== observer)
219​
220 this.scheduleGc()
221​
222 this.#mutationCache.notify({
223 type: 'observerRemoved',
224 mutation: this,
225 observer,
226 })
227 }
228​
229 protected override optionalRemove() {
230 if (!this.#observers.length) {
231 if (this.state.status === 'pending') {
232 this.scheduleGc()
233 } else {
234 this.#mutationCache.remove(this)
235 }
236 }
237 }
238​
239 /**
240 * Resumes a mutation that is currently paused or was restored from a
241 * dehydrated, still-`pending` state.
242 *
243 * - If this mutation has an active retryer (it paused mid-attempt, e.g. due
244 * to the network mode or scope-based queuing), its retryer is resumed.
245 * - Otherwise, if the mutation's status is still `pending` (e.g. it was
246 * dehydrated while an attempt was in flight and never got a retryer in
247 * this instance), `execute` is called again with the last known variables.
248 * - Otherwise the mutation has already settled and this resolves immediately
249 * without running anything again.
250 * @returns A promise that settles with the resumed mutation: it rejects if the mutation fails.
251 * It resolves immediately if the mutation has already settled.
252 * @see {@link Mutation#execute}
253 * @example
254 * ```ts
255 * // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
256 * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
257 * await mutation?.continue()
258 * ```
259 */
260 continue(): Promise<unknown> {
261 return (
262 this.#retryer?.continue() ??
263 // continuing a mutation assumes that variables are set, mutation must have been dehydrated before.
264 // a settled mutation has no retryer to continue and must not run again
265 (this.state.status === 'pending'
266 ? this.execute(this.state.variables!)
267 : Promise.resolve())
268 )
269 }
270​
271 /**
272 * Runs the mutation function for the given variables through a retryer, and
273 * drives the mutation's state and lifecycle callbacks through to settlement.
274 *
275 * If this mutation's state is already `pending` when `execute` is called
276 * (i.e. it was restored, still in-flight, from a dehydrated state), the
277 * `onMutate` step is skipped and a `continue` action is dispatched to
278 * unpause it; otherwise a `pending` action is dispatched first, then the
279 * mutation cache's `onMutate` and the mutation's own `onMutate` option are
280 * awaited in that order, and the resulting context is stored.
281 *
282 * The mutation function is then run (subject to `retry`/`retryDelay`/
283 * `networkMode`, and to the mutation cache's scope-based serialization).
284 * On success, the cache's `onSuccess`/`onSettled` callbacks run before the
285 * mutation's own `onSuccess`/`onSettled` options, a `success` action is
286 * dispatched, and the resolved data is returned. On failure, the same
287 * cache-then-option ordering is used for `onError`/`onSettled`, but each of
288 * those four callbacks is individually caught so that a throwing callback
289 * cannot mask the original error; an `error` action is then dispatched and
290 * the original error is re-thrown.
291 * @param variables - The variables passed to the `mutationFn`.
292 * @returns A promise that resolves with the mutation's data, or rejects with its error.
293 * @see {@link Mutation#continue}
294 * @example
295 * ```ts
296 * // Called internally by `MutationObserver.mutate` and `Mutation.continue` β€”
297 * // applications normally trigger mutations through those, not this method.
298 * const data = await mutation.execute(variables)
299 * ```
300 */
301 async execute(variables: TVariables): Promise<TData> {
302 const onContinue = () => {
303 this.#dispatch({ type: 'continue' })
304 }
305​
306 const mutationFnContext = {
307 client: this.#client,
308 meta: this.options.meta,
309 mutationKey: this.options.mutationKey,
310 } satisfies MutationFunctionContext
311​
312 const retryer = (this.#retryer = createRetryer({
313 fn: () => {
314 if (!this.options.mutationFn) {
315 return Promise.reject(new Error('No mutationFn found'))
316 }
317​
318 return this.options.mutationFn(variables, mutationFnContext)
319 },
320 onFail: (failureCount, error) => {
321 this.#dispatch({ type: 'failed', failureCount, error })
322 },
323 onPause: () => {
324 this.#dispatch({ type: 'pause' })
325 },
326 onContinue,
327 retry: this.options.retry ?? 0,
328 retryDelay: this.options.retryDelay,
329 networkMode: this.options.networkMode,
330 canRun: () => this.#mutationCache.canRun(this),
331 }))
332​
333 const restored = this.state.status === 'pending'
334 const isPaused = !retryer.canStart()
335​
336 try {
337 if (restored) {
338 // Dispatch continue action to unpause restored mutation
339 onContinue()
340 } else {
341 this.#dispatch({ type: 'pending', variables, isPaused })
342 // Notify cache callback
343 if (this.#mutationCache.config.onMutate) {
344 await this.#mutationCache.config.onMutate(
345 variables,
346 this as Mutation<unknown, unknown, unknown, unknown>,
347 mutationFnContext,
348 )
349 }
350 const context = await this.options.onMutate?.(
351 variables,
352 mutationFnContext,
353 )
354 if (context !== this.state.context) {
355 this.#dispatch({
356 type: 'pending',
357 context,
358 variables,
359 isPaused,
360 })
361 }
362 }
363 // Unpause a mutation that became able to start while onMutate was running
364 if (this.state.isPaused && retryer.canStart()) {
365 onContinue()
366 }
367 const data = await retryer.start()
368​
369 // Notify cache callback
370 await this.#mutationCache.config.onSuccess?.(
371 data,
372 variables,
373 this.state.context,
374 this as Mutation<unknown, unknown, unknown, unknown>,
375 mutationFnContext,
376 )
377​
378 await this.options.onSuccess?.(
379 data,
380 variables,
381 this.state.context!,
382 mutationFnContext,
383 )
384​
385 // Notify cache callback
386 await this.#mutationCache.config.onSettled?.(
387 data,
388 null,
389 this.state.variables,
390 this.state.context,
391 this as Mutation<unknown, unknown, unknown, unknown>,
392 mutationFnContext,
393 )
394​
395 await this.options.onSettled?.(
396 data,
397 null,
398 variables,
399 this.state.context,
400 mutationFnContext,
401 )
402​
403 this.#dispatch({ type: 'success', data })
404 return data
405 } catch (error) {
406 try {
407 // Notify cache callback
408 await this.#mutationCache.config.onError?.(
409 error as any,
410 variables,
411 this.state.context,
412 this as Mutation<unknown, unknown, unknown, unknown>,
413 mutationFnContext,
414 )
415 } catch (e) {
416 void Promise.reject(e)
417 }
418​
419 try {
420 await this.options.onError?.(
421 error as TError,
422 variables,
423 this.state.context,
424 mutationFnContext,
425 )
426 } catch (e) {
427 void Promise.reject(e)
428 }
429​
430 try {
431 // Notify cache callback
432 await this.#mutationCache.config.onSettled?.(
433 undefined,
434 error as any,
435 this.state.variables,
436 this.state.context,
437 this as Mutation<unknown, unknown, unknown, unknown>,
438 mutationFnContext,
439 )
440 } catch (e) {
441 void Promise.reject(e)
442 }
443​
444 try {
445 await this.options.onSettled?.(
446 undefined,
447 error as TError,
448 variables,
449 this.state.context,
450 mutationFnContext,
451 )
452 } catch (e) {
453 void Promise.reject(e)
454 }
455​
456 this.#dispatch({ type: 'error', error: error as TError })
457 throw error
458 } finally {
459 // The settled retryer's promise would otherwise pin this mutation's
460 // result, variables and context for as long as the cache keeps it
461 if (this.#retryer === retryer) {
462 this.#retryer = undefined
463 }
464 this.#mutationCache.runNext(this)
465 }
466 }
467​
468 #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {
469 const reducer = (
470 state: MutationState<TData, TError, TVariables, TOnMutateResult>,
471 ): MutationState<TData, TError, TVariables, TOnMutateResult> => {
472 switch (action.type) {
473 case 'failed':
474 return {
475 ...state,
476 failureCount: action.failureCount,
477 failureReason: action.error,
478 }
479 case 'pause':
480 return {
481 ...state,
482 isPaused: true,
483 }
484 case 'continue':
485 return {
486 ...state,
487 isPaused: false,
488 }
489 case 'pending':
490 return {
491 ...state,
492 context: action.context,
493 data: undefined,
494 failureCount: 0,
495 failureReason: null,
496 error: null,
497 isPaused: action.isPaused,
498 status: 'pending',
499 variables: action.variables,
500 submittedAt: Date.now(),
501 }
502 case 'success':
503 return {
504 ...state,
505 data: action.data,
506 failureCount: 0,
507 failureReason: null,
508 error: null,
509 status: 'success',
510 isPaused: false,
511 }
512 case 'error':
513 return {
514 ...state,
515 data: undefined,
516 error: action.error,
517 failureCount: state.failureCount + 1,
518 failureReason: action.error,
519 isPaused: false,
520 status: 'error',
521 }
522 }
523 }
524 this.state = reducer(this.state)
525​
526 notifyManager.batch(() => {
527 this.#observers.forEach((observer) => {
528 observer.onMutationUpdate(action)
529 })
530 this.#mutationCache.notify({
531 mutation: this,
532 type: 'updated',
533 action,
534 })
535 })
536 }
538​
539/**
540 * Returns the initial state of a mutation: `'idle'`, with no data, error, or variables.
541 * @returns The initial mutation state.
542 */
543export function getDefaultState<
544 TData,
545 TError,
546 TVariables,
547 TOnMutateResult,
548>(): MutationState<TData, TError, TVariables, TOnMutateResult> {
549 return {
550 context: undefined,
551 data: undefined,
552 error: null,
553 failureCount: 0,
554 failureReason: null,
555 isPaused: false,
556 status: 'idle',
557 variables: undefined,
558 submittedAt: 0,
559 }