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

mutation.ts

378 lines9.3 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, TContext> {
19 client: QueryClient
20 mutationId: number
21 mutationCache: MutationCache
22 options: MutationOptions<TData, TError, TVariables, TContext>
23 state?: MutationState<TData, TError, TVariables, TContext>
25​
26export interface MutationState<
27 TData = unknown,
28 TError = DefaultError,
29 TVariables = unknown,
30 TContext = unknown,
31> {
32 context: TContext | undefined
33 data: TData | undefined
34 error: TError | null
35 failureCount: number
36 failureReason: TError | null
37 isPaused: boolean
38 status: MutationStatus
39 variables: TVariables | undefined
40 submittedAt: number
42​
43interface FailedAction<TError> {
44 type: 'failed'
45 failureCount: number
46 error: TError | null
48​
49interface PendingAction<TVariables, TContext> {
50 type: 'pending'
51 isPaused: boolean
52 variables?: TVariables
53 context?: TContext
55​
56interface SuccessAction<TData> {
57 type: 'success'
58 data: TData
60​
61interface ErrorAction<TError> {
62 type: 'error'
63 error: TError
65​
66interface PauseAction {
67 type: 'pause'
69​
70interface ContinueAction {
71 type: 'continue'
73​
74export type Action<TData, TError, TVariables, TContext> =
75 | ContinueAction
76 | ErrorAction<TError>
77 | FailedAction<TError>
78 | PendingAction<TVariables, TContext>
79 | PauseAction
80 | SuccessAction<TData>
81​
82// CLASS
83​
84export class Mutation<
85 TData = unknown,
86 TError = DefaultError,
87 TVariables = unknown,
88 TContext = unknown,
89> extends Removable {
90 state: MutationState<TData, TError, TVariables, TContext>
91 options!: MutationOptions<TData, TError, TVariables, TContext>
92 readonly mutationId: number
93​
94 #client: QueryClient
95 #observers: Array<MutationObserver<TData, TError, TVariables, TContext>>
96 #mutationCache: MutationCache
97 #retryer?: Retryer<TData>
98​
99 constructor(config: MutationConfig<TData, TError, TVariables, TContext>) {
100 super()
101​
102 this.#client = config.client
103 this.mutationId = config.mutationId
104 this.#mutationCache = config.mutationCache
105 this.#observers = []
106 this.state = config.state || getDefaultState()
107​
108 this.setOptions(config.options)
109 this.scheduleGc()
110 }
111​
112 setOptions(
113 options: MutationOptions<TData, TError, TVariables, TContext>,
114 ): void {
115 this.options = options
116​
117 this.updateGcTime(this.options.gcTime)
118 }
119​
120 get meta(): MutationMeta | undefined {
121 return this.options.meta
122 }
123​
124 addObserver(observer: MutationObserver<any, any, any, any>): void {
125 if (!this.#observers.includes(observer)) {
126 this.#observers.push(observer)
127​
128 // Stop the mutation from being garbage collected
129 this.clearGcTimeout()
130​
131 this.#mutationCache.notify({
132 type: 'observerAdded',
133 mutation: this,
134 observer,
135 })
136 }
137 }
138​
139 removeObserver(observer: MutationObserver<any, any, any, any>): void {
140 this.#observers = this.#observers.filter((x) => x !== observer)
141​
142 this.scheduleGc()
143​
144 this.#mutationCache.notify({
145 type: 'observerRemoved',
146 mutation: this,
147 observer,
148 })
149 }
150​
151 protected optionalRemove() {
152 if (!this.#observers.length) {
153 if (this.state.status === 'pending') {
154 this.scheduleGc()
155 } else {
156 this.#mutationCache.remove(this)
157 }
158 }
159 }
160​
161 continue(): Promise<unknown> {
162 return (
163 this.#retryer?.continue() ??
164 // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
165 this.execute(this.state.variables!)
166 )
167 }
168​
169 async execute(variables: TVariables): Promise<TData> {
170 const onContinue = () => {
171 this.#dispatch({ type: 'continue' })
172 }
173​
174 this.#retryer = createRetryer({
175 fn: () => {
176 if (!this.options.mutationFn) {
177 return Promise.reject(new Error('No mutationFn found'))
178 }
179​
180 const mutationFnContext: MutationFunctionContext = {
181 client: this.#client,
182 meta: this.options.meta,
183 mutationKey: this.options.mutationKey,
184 }
185​
186 return this.options.mutationFn(variables, mutationFnContext)
187 },
188 onFail: (failureCount, error) => {
189 this.#dispatch({ type: 'failed', failureCount, error })
190 },
191 onPause: () => {
192 this.#dispatch({ type: 'pause' })
193 },
194 onContinue,
195 retry: this.options.retry ?? 0,
196 retryDelay: this.options.retryDelay,
197 networkMode: this.options.networkMode,
198 canRun: () => this.#mutationCache.canRun(this),
199 })
200​
201 const restored = this.state.status === 'pending'
202 const isPaused = !this.#retryer.canStart()
203​
204 try {
205 if (restored) {
206 // Dispatch continue action to unpause restored mutation
207 onContinue()
208 } else {
209 this.#dispatch({ type: 'pending', variables, isPaused })
210 // Notify cache callback
211 await this.#mutationCache.config.onMutate?.(
212 variables,
213 this as Mutation<unknown, unknown, unknown, unknown>,
214 )
215 const context = await this.options.onMutate?.(variables)
216 if (context !== this.state.context) {
217 this.#dispatch({
218 type: 'pending',
219 context,
220 variables,
221 isPaused,
222 })
223 }
224 }
225 const data = await this.#retryer.start()
226​
227 // Notify cache callback
228 await this.#mutationCache.config.onSuccess?.(
229 data,
230 variables,
231 this.state.context,
232 this as Mutation<unknown, unknown, unknown, unknown>,
233 )
234​
235 await this.options.onSuccess?.(data, variables, this.state.context!)
236​
237 // Notify cache callback
238 await this.#mutationCache.config.onSettled?.(
239 data,
240 null,
241 this.state.variables,
242 this.state.context,
243 this as Mutation<unknown, unknown, unknown, unknown>,
244 )
245​
246 await this.options.onSettled?.(data, null, variables, this.state.context)
247​
248 this.#dispatch({ type: 'success', data })
249 return data
250 } catch (error) {
251 try {
252 // Notify cache callback
253 await this.#mutationCache.config.onError?.(
254 error as any,
255 variables,
256 this.state.context,
257 this as Mutation<unknown, unknown, unknown, unknown>,
258 )
259​
260 await this.options.onError?.(
261 error as TError,
262 variables,
263 this.state.context,
264 )
265​
266 // Notify cache callback
267 await this.#mutationCache.config.onSettled?.(
268 undefined,
269 error as any,
270 this.state.variables,
271 this.state.context,
272 this as Mutation<unknown, unknown, unknown, unknown>,
273 )
274​
275 await this.options.onSettled?.(
276 undefined,
277 error as TError,
278 variables,
279 this.state.context,
280 )
281 throw error
282 } finally {
283 this.#dispatch({ type: 'error', error: error as TError })
284 }
285 } finally {
286 this.#mutationCache.runNext(this)
287 }
288 }
289​
290 #dispatch(action: Action<TData, TError, TVariables, TContext>): void {
291 const reducer = (
292 state: MutationState<TData, TError, TVariables, TContext>,
293 ): MutationState<TData, TError, TVariables, TContext> => {
294 switch (action.type) {
295 case 'failed':
296 return {
297 ...state,
298 failureCount: action.failureCount,
299 failureReason: action.error,
300 }
301 case 'pause':
302 return {
303 ...state,
304 isPaused: true,
305 }
306 case 'continue':
307 return {
308 ...state,
309 isPaused: false,
310 }
311 case 'pending':
312 return {
313 ...state,
314 context: action.context,
315 data: undefined,
316 failureCount: 0,
317 failureReason: null,
318 error: null,
319 isPaused: action.isPaused,
320 status: 'pending',
321 variables: action.variables,
322 submittedAt: Date.now(),
323 }
324 case 'success':
325 return {
326 ...state,
327 data: action.data,
328 failureCount: 0,
329 failureReason: null,
330 error: null,
331 status: 'success',
332 isPaused: false,
333 }
334 case 'error':
335 return {
336 ...state,
337 data: undefined,
338 error: action.error,
339 failureCount: state.failureCount + 1,
340 failureReason: action.error,
341 isPaused: false,
342 status: 'error',
343 }
344 }
345 }
346 this.state = reducer(this.state)
347​
348 notifyManager.batch(() => {
349 this.#observers.forEach((observer) => {
350 observer.onMutationUpdate(action)
351 })
352 this.#mutationCache.notify({
353 mutation: this,
354 type: 'updated',
355 action,
356 })
357 })
358 }
360​
361export function getDefaultState<
362 TData,
363 TError,
364 TVariables,
365 TContext,
366>(): MutationState<TData, TError, TVariables, TContext> {
367 return {
368 context: undefined,
369 data: undefined,
370 error: null,
371 failureCount: 0,
372 failureReason: null,
373 isPaused: false,
374 status: 'idle',
375 variables: undefined,
376 submittedAt: 0,
377 }