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