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

mutation.ts

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