Open History to see the last commit
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>
24}
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
75}
76β
77interface FailedAction<TError> {
78 type: 'failed'
79 failureCount: number
80 error: TError | null
81}
82β
83interface PendingAction<TVariables, TOnMutateResult> {
84 type: 'pending'
85 isPaused: boolean
86 variables?: TVariables
87 context?: TOnMutateResult
88}
89β
90interface SuccessAction<TData> {
91 type: 'success'
92 data: TData
93}
94β
95interface ErrorAction<TError> {
96 type: 'error'
97 error: TError
98}
99β
100interface PauseAction {
101 type: 'pause'
102}
103β
104interface ContinueAction {
105 type: 'continue'
106}
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 const data = await retryer.start()
364β
365 // Notify cache callback
366 await this.#mutationCache.config.onSuccess?.(
367 data,
368 variables,
369 this.state.context,
370 this as Mutation<unknown, unknown, unknown, unknown>,
371 mutationFnContext,
372 )
373β
374 await this.options.onSuccess?.(
375 data,
376 variables,
377 this.state.context!,
378 mutationFnContext,
379 )
380β
381 // Notify cache callback
382 await this.#mutationCache.config.onSettled?.(
383 data,
384 null,
385 this.state.variables,
386 this.state.context,
387 this as Mutation<unknown, unknown, unknown, unknown>,
388 mutationFnContext,
389 )
390β
391 await this.options.onSettled?.(
392 data,
393 null,
394 variables,
395 this.state.context,
396 mutationFnContext,
397 )
398β
399 this.#dispatch({ type: 'success', data })
400 return data
401 } catch (error) {
402 try {
403 // Notify cache callback
404 await this.#mutationCache.config.onError?.(
405 error as any,
406 variables,
407 this.state.context,
408 this as Mutation<unknown, unknown, unknown, unknown>,
409 mutationFnContext,
410 )
411 } catch (e) {
412 void Promise.reject(e)
413 }
414β
415 try {
416 await this.options.onError?.(
417 error as TError,
418 variables,
419 this.state.context,
420 mutationFnContext,
421 )
422 } catch (e) {
423 void Promise.reject(e)
424 }
425β
426 try {
427 // Notify cache callback
428 await this.#mutationCache.config.onSettled?.(
429 undefined,
430 error as any,
431 this.state.variables,
432 this.state.context,
433 this as Mutation<unknown, unknown, unknown, unknown>,
434 mutationFnContext,
435 )
436 } catch (e) {
437 void Promise.reject(e)
438 }
439β
440 try {
441 await this.options.onSettled?.(
442 undefined,
443 error as TError,
444 variables,
445 this.state.context,
446 mutationFnContext,
447 )
448 } catch (e) {
449 void Promise.reject(e)
450 }
451β
452 this.#dispatch({ type: 'error', error: error as TError })
453 throw error
454 } finally {
455 // The settled retryer's promise would otherwise pin this mutation's
456 // result, variables and context for as long as the cache keeps it
457 if (this.#retryer === retryer) {
458 this.#retryer = undefined
459 }
460 this.#mutationCache.runNext(this)
461 }
462 }
463β
464 #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {
465 const reducer = (
466 state: MutationState<TData, TError, TVariables, TOnMutateResult>,
467 ): MutationState<TData, TError, TVariables, TOnMutateResult> => {
468 switch (action.type) {
469 case 'failed':
470 return {
471 ...state,
472 failureCount: action.failureCount,
473 failureReason: action.error,
474 }
475 case 'pause':
476 return {
477 ...state,
478 isPaused: true,
479 }
480 case 'continue':
481 return {
482 ...state,
483 isPaused: false,
484 }
485 case 'pending':
486 return {
487 ...state,
488 context: action.context,
489 data: undefined,
490 failureCount: 0,
491 failureReason: null,
492 error: null,
493 isPaused: action.isPaused,
494 status: 'pending',
495 variables: action.variables,
496 submittedAt: Date.now(),
497 }
498 case 'success':
499 return {
500 ...state,
501 data: action.data,
502 failureCount: 0,
503 failureReason: null,
504 error: null,
505 status: 'success',
506 isPaused: false,
507 }
508 case 'error':
509 return {
510 ...state,
511 data: undefined,
512 error: action.error,
513 failureCount: state.failureCount + 1,
514 failureReason: action.error,
515 isPaused: false,
516 status: 'error',
517 }
518 }
519 }
520 this.state = reducer(this.state)
521β
522 notifyManager.batch(() => {
523 this.#observers.forEach((observer) => {
524 observer.onMutationUpdate(action)
525 })
526 this.#mutationCache.notify({
527 mutation: this,
528 type: 'updated',
529 action,
530 })
531 })
532 }
533}
534β
535/**
536 * Returns the initial state of a mutation: `'idle'`, with no data, error, or variables.
537 * @returns The initial mutation state.
538 */
539export function getDefaultState<
540 TData,
541 TError,
542 TVariables,
543 TOnMutateResult,
544>(): MutationState<TData, TError, TVariables, TOnMutateResult> {
545 return {
546 context: undefined,
547 data: undefined,
548 error: null,
549 failureCount: 0,
550 failureReason: null,
551 isPaused: false,
552 status: 'idle',
553 variables: undefined,
554 submittedAt: 0,
555 }
556}