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

mutation.ts

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