Open History to see the last commit
1import { notifyManager } from './notifyManager'
2import { Removable } from './removable'
3import { createRetryer } from './retryer'
4import type { MutationCache } from './mutationCache'
5import type { MutationObserver } from './mutationObserver'
6import type { QueryClient } from './queryClient'
7import type { Retryer } from './retryer'
8import type {
9 DefaultError,
10 MutationFunctionContext,
11 MutationMeta,
12 MutationOptions,
13 MutationStatus,
14} from './types'
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. Schedules garbage collection if the mutation
216 * is still in the cache.
217 */
218 removeObserver(observer: MutationObserver<any, any, any, any>): void {
219 this.#observers = this.#observers.filter((x) => x !== observer)
220β
221 if (this.#mutationCache.has(this)) {
222 this.scheduleGc()
223 }
224β
225 this.#mutationCache.notify({
226 type: 'observerRemoved',
227 mutation: this,
228 observer,
229 })
230 }
231β
232 protected override optionalRemove() {
233 if (!this.#observers.length) {
234 if (this.state.status === 'pending') {
235 this.scheduleGc()
236 } else {
237 this.#mutationCache.remove(this)
238 }
239 }
240 }
241β
242 /**
243 * Resumes a mutation that is currently paused or was restored from a
244 * dehydrated, still-`pending` state.
245 *
246 * - If this mutation has an active retryer (it paused mid-attempt, e.g. due
247 * to the network mode or scope-based queuing), its retryer is resumed.
248 * - Otherwise, if the mutation's status is still `pending` (e.g. it was
249 * dehydrated while an attempt was in flight and never got a retryer in
250 * this instance), `execute` is called again with the last known variables.
251 * - Otherwise the mutation has already settled and this resolves immediately
252 * without running anything again.
253 * @returns A promise that settles with the resumed mutation: it rejects if the mutation fails.
254 * It resolves immediately if the mutation has already settled.
255 * @see {@link Mutation#execute}
256 * @example
257 * ```ts
258 * // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()
259 * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
260 * await mutation?.continue()
261 * ```
262 */
263 continue(): Promise<unknown> {
264 return (
265 this.#retryer?.continue() ??
266 // continuing a mutation assumes that variables are set, mutation must have been dehydrated before.
267 // a settled mutation has no retryer to continue and must not run again
268 (this.state.status === 'pending'
269 ? this.execute(this.state.variables!)
270 : Promise.resolve())
271 )
272 }
273β
274 /**
275 * Runs the mutation function for the given variables through a retryer, and
276 * drives the mutation's state and lifecycle callbacks through to settlement.
277 *
278 * If this mutation's state is already `pending` when `execute` is called
279 * (i.e. it was restored, still in-flight, from a dehydrated state), the
280 * `onMutate` step is skipped and a `continue` action is dispatched to
281 * unpause it; otherwise a `pending` action is dispatched first, then the
282 * mutation cache's `onMutate` and the mutation's own `onMutate` option are
283 * awaited in that order, and the resulting context is stored.
284 *
285 * The mutation function is then run (subject to `retry`/`retryDelay`/
286 * `networkMode`, and to the mutation cache's scope-based serialization).
287 * On success, the cache's `onSuccess`/`onSettled` callbacks run before the
288 * mutation's own `onSuccess`/`onSettled` options, a `success` action is
289 * dispatched, and the resolved data is returned. On failure, the same
290 * cache-then-option ordering is used for `onError`/`onSettled`, but each of
291 * those four callbacks is individually caught so that a throwing callback
292 * cannot mask the original error; an `error` action is then dispatched and
293 * the original error is re-thrown.
294 * @param variables - The variables passed to the `mutationFn`.
295 * @returns A promise that resolves with the mutation's data, or rejects with its error.
296 * @see {@link Mutation#continue}
297 * @example
298 * ```ts
299 * // Called internally by `MutationObserver.mutate` and `Mutation.continue` β
300 * // applications normally trigger mutations through those, not this method.
301 * const data = await mutation.execute(variables)
302 * ```
303 */
304 async execute(variables: TVariables): Promise<TData> {
305 const onContinue = () => {
306 this.#dispatch({ type: 'continue' })
307 }
308β
309 const mutationFnContext = {
310 client: this.#client,
311 meta: this.options.meta,
312 mutationKey: this.options.mutationKey,
313 } satisfies MutationFunctionContext
314β
315 const retryer = (this.#retryer = createRetryer({
316 fn: () => {
317 if (!this.options.mutationFn) {
318 return Promise.reject(new Error('No mutationFn found'))
319 }
320β
321 return this.options.mutationFn(variables, mutationFnContext)
322 },
323 onFail: (failureCount, error) => {
324 this.#dispatch({ type: 'failed', failureCount, error })
325 },
326 onPause: () => {
327 this.#dispatch({ type: 'pause' })
328 },
329 onContinue,
330 retry: this.options.retry ?? 0,
331 retryDelay: this.options.retryDelay,
332 networkMode: this.options.networkMode,
333 canRun: () => this.#mutationCache.canRun(this),
334 }))
335β
336 const restored = this.state.status === 'pending'
337 const isPaused = !retryer.canStart()
338β
339 try {
340 if (restored) {
341 // Dispatch continue action to unpause restored mutation
342 onContinue()
343 } else {
344 this.#dispatch({ type: 'pending', variables, isPaused })
345 // Notify cache callback
346 if (this.#mutationCache.config.onMutate) {
347 await this.#mutationCache.config.onMutate(
348 variables,
349 this as Mutation<unknown, unknown, unknown, unknown>,
350 mutationFnContext,
351 )
352 }
353 const context = await this.options.onMutate?.(
354 variables,
355 mutationFnContext,
356 )
357 if (context !== this.state.context) {
358 this.#dispatch({
359 type: 'pending',
360 context,
361 variables,
362 isPaused,
363 })
364 }
365 }
366 // Unpause a mutation that became able to start while onMutate was running
367 if (this.state.isPaused && retryer.canStart()) {
368 onContinue()
369 }
370 const data = await retryer.start()
371β
372 // Notify cache callback
373 await this.#mutationCache.config.onSuccess?.(
374 data,
375 variables,
376 this.state.context,
377 this as Mutation<unknown, unknown, unknown, unknown>,
378 mutationFnContext,
379 )
380β
381 await this.options.onSuccess?.(
382 data,
383 variables,
384 this.state.context!,
385 mutationFnContext,
386 )
387β
388 // Notify cache callback
389 await this.#mutationCache.config.onSettled?.(
390 data,
391 null,
392 this.state.variables,
393 this.state.context,
394 this as Mutation<unknown, unknown, unknown, unknown>,
395 mutationFnContext,
396 )
397β
398 await this.options.onSettled?.(
399 data,
400 null,
401 variables,
402 this.state.context,
403 mutationFnContext,
404 )
405β
406 this.#dispatch({ type: 'success', data })
407 return data
408 } catch (error) {
409 try {
410 // Notify cache callback
411 await this.#mutationCache.config.onError?.(
412 error as any,
413 variables,
414 this.state.context,
415 this as Mutation<unknown, unknown, unknown, unknown>,
416 mutationFnContext,
417 )
418 } catch (e) {
419 void Promise.reject(e)
420 }
421β
422 try {
423 await this.options.onError?.(
424 error as TError,
425 variables,
426 this.state.context,
427 mutationFnContext,
428 )
429 } catch (e) {
430 void Promise.reject(e)
431 }
432β
433 try {
434 // Notify cache callback
435 await this.#mutationCache.config.onSettled?.(
436 undefined,
437 error as any,
438 this.state.variables,
439 this.state.context,
440 this as Mutation<unknown, unknown, unknown, unknown>,
441 mutationFnContext,
442 )
443 } catch (e) {
444 void Promise.reject(e)
445 }
446β
447 try {
448 await this.options.onSettled?.(
449 undefined,
450 error as TError,
451 variables,
452 this.state.context,
453 mutationFnContext,
454 )
455 } catch (e) {
456 void Promise.reject(e)
457 }
458β
459 this.#dispatch({ type: 'error', error: error as TError })
460 throw error
461 } finally {
462 // The settled retryer's promise would otherwise pin this mutation's
463 // result, variables and context for as long as the cache keeps it
464 if (this.#retryer === retryer) {
465 this.#retryer = undefined
466 }
467 this.#mutationCache.runNext(this)
468 }
469 }
470β
471 #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {
472 const reducer = (
473 state: MutationState<TData, TError, TVariables, TOnMutateResult>,
474 ): MutationState<TData, TError, TVariables, TOnMutateResult> => {
475 switch (action.type) {
476 case 'failed':
477 return {
478 ...state,
479 failureCount: action.failureCount,
480 failureReason: action.error,
481 }
482 case 'pause':
483 return {
484 ...state,
485 isPaused: true,
486 }
487 case 'continue':
488 return {
489 ...state,
490 isPaused: false,
491 }
492 case 'pending':
493 return {
494 ...state,
495 context: action.context,
496 data: undefined,
497 failureCount: 0,
498 failureReason: null,
499 error: null,
500 isPaused: action.isPaused,
501 status: 'pending',
502 variables: action.variables,
503 submittedAt: Date.now(),
504 }
505 case 'success':
506 return {
507 ...state,
508 data: action.data,
509 failureCount: 0,
510 failureReason: null,
511 error: null,
512 status: 'success',
513 isPaused: false,
514 }
515 case 'error':
516 return {
517 ...state,
518 data: undefined,
519 error: action.error,
520 failureCount: state.failureCount + 1,
521 failureReason: action.error,
522 isPaused: false,
523 status: 'error',
524 }
525 }
526 }
527 this.state = reducer(this.state)
528β
529 notifyManager.batch(() => {
530 this.#observers.forEach((observer) => {
531 observer.onMutationUpdate(action)
532 })
533 this.#mutationCache.notify({
534 mutation: this,
535 type: 'updated',
536 action,
537 })
538 })
539 }
540}
541β
542/**
543 * Returns the initial state of a mutation: `'idle'`, with no data, error, or variables.
544 * @returns The initial mutation state.
545 */
546export function getDefaultState<
547 TData,
548 TError,
549 TVariables,
550 TOnMutateResult,
551>(): MutationState<TData, TError, TVariables, TOnMutateResult> {
552 return {
553 context: undefined,
554 data: undefined,
555 error: null,
556 failureCount: 0,
557 failureReason: null,
558 isPaused: false,
559 status: 'idle',
560 variables: undefined,
561 submittedAt: 0,
562 }
563}