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

mutation.ts

351 lines8.6 KB

1import type { MutationOptions, MutationStatus, MutationMeta } from './types'
2import type { MutationCache } from './mutationCache'
3import type { MutationObserver } from './mutationObserver'
4import type { Logger } from './logger'
5import { defaultLogger } from './logger'
6import { notifyManager } from './notifyManager'
7import { Removable } from './removable'
8import type { Retryer } from './retryer'
9import { canFetch, createRetryer } from './retryer'
10​
11// TYPES
12​
13interface MutationConfig<TData, TError, TVariables, TContext> {
14 mutationId: number
15 mutationCache: MutationCache
16 options: MutationOptions<TData, TError, TVariables, TContext>
17 logger?: Logger
18 defaultOptions?: MutationOptions<TData, TError, TVariables, TContext>
19 state?: MutationState<TData, TError, TVariables, TContext>
20 meta?: MutationMeta
22​
23export interface MutationState<
24 TData = unknown,
25 TError = unknown,
26 TVariables = void,
27 TContext = unknown,
28> {
29 context: TContext | undefined
30 data: TData | undefined
31 error: TError | null
32 failureCount: number
33 isPaused: boolean
34 status: MutationStatus
35 variables: TVariables | undefined
37​
38interface FailedAction {
39 type: 'failed'
41​
42interface LoadingAction<TVariables, TContext> {
43 type: 'loading'
44 variables?: TVariables
45 context?: TContext
47​
48interface SuccessAction<TData> {
49 type: 'success'
50 data: TData
52​
53interface ErrorAction<TError> {
54 type: 'error'
55 error: TError
57​
58interface PauseAction {
59 type: 'pause'
61​
62interface ContinueAction {
63 type: 'continue'
65​
66interface SetStateAction<TData, TError, TVariables, TContext> {
67 type: 'setState'
68 state: MutationState<TData, TError, TVariables, TContext>
70​
71export type Action<TData, TError, TVariables, TContext> =
72 | ContinueAction
73 | ErrorAction<TError>
74 | FailedAction
75 | LoadingAction<TVariables, TContext>
76 | PauseAction
77 | SetStateAction<TData, TError, TVariables, TContext>
78 | SuccessAction<TData>
79​
80// CLASS
81​
82export class Mutation<
83 TData = unknown,
84 TError = unknown,
85 TVariables = void,
86 TContext = unknown,
87> extends Removable {
88 state: MutationState<TData, TError, TVariables, TContext>
89 options: MutationOptions<TData, TError, TVariables, TContext>
90 mutationId: number
91 meta: MutationMeta | undefined
92​
93 private observers: MutationObserver<TData, TError, TVariables, TContext>[]
94 private mutationCache: MutationCache
95 private logger: Logger
96 private retryer?: Retryer<TData>
97​
98 constructor(config: MutationConfig<TData, TError, TVariables, TContext>) {
99 super()
100​
101 this.options = {
102 ...config.defaultOptions,
103 ...config.options,
104 }
105 this.mutationId = config.mutationId
106 this.mutationCache = config.mutationCache
107 this.logger = config.logger || defaultLogger
108 this.observers = []
109 this.state = config.state || getDefaultState()
110 this.meta = config.meta
111​
112 this.updateCacheTime(this.options.cacheTime)
113 this.scheduleGc()
114 }
115​
116 setState(state: MutationState<TData, TError, TVariables, TContext>): void {
117 this.dispatch({ type: 'setState', state })
118 }
119​
120 addObserver(observer: MutationObserver<any, any, any, any>): void {
121 if (this.observers.indexOf(observer) === -1) {
122 this.observers.push(observer)
123​
124 // Stop the mutation from being garbage collected
125 this.clearGcTimeout()
126​
127 this.mutationCache.notify({
128 type: 'observerAdded',
129 mutation: this,
130 observer,
131 })
132 }
133 }
134​
135 removeObserver(observer: MutationObserver<any, any, any, any>): void {
136 this.observers = this.observers.filter((x) => x !== observer)
137​
138 this.scheduleGc()
139​
140 this.mutationCache.notify({
141 type: 'observerRemoved',
142 mutation: this,
143 observer,
144 })
145 }
146​
147 protected optionalRemove() {
148 if (!this.observers.length) {
149 if (this.state.status === 'loading') {
150 this.scheduleGc()
151 } else {
152 this.mutationCache.remove(this)
153 }
154 }
155 }
156​
157 continue(): Promise<TData> {
158 if (this.retryer) {
159 this.retryer.continue()
160 return this.retryer.promise
161 }
162 return this.execute()
163 }
164​
165 async execute(): Promise<TData> {
166 const executeMutation = () => {
167 this.retryer = createRetryer({
168 fn: () => {
169 if (!this.options.mutationFn) {
170 return Promise.reject('No mutationFn found')
171 }
172 return this.options.mutationFn(this.state.variables!)
173 },
174 onFail: () => {
175 this.dispatch({ type: 'failed' })
176 },
177 onPause: () => {
178 this.dispatch({ type: 'pause' })
179 },
180 onContinue: () => {
181 this.dispatch({ type: 'continue' })
182 },
183 retry: this.options.retry ?? 0,
184 retryDelay: this.options.retryDelay,
185 networkMode: this.options.networkMode,
186 })
187​
188 return this.retryer.promise
189 }
190​
191 const restored = this.state.status === 'loading'
192 try {
193 if (!restored) {
194 this.dispatch({ type: 'loading', variables: this.options.variables! })
195 // Notify cache callback
196 this.mutationCache.config.onMutate?.(
197 this.state.variables,
198 this as Mutation<unknown, unknown, unknown, unknown>,
199 )
200 const context = await this.options.onMutate?.(this.state.variables!)
201 if (context !== this.state.context) {
202 this.dispatch({
203 type: 'loading',
204 context,
205 variables: this.state.variables,
206 })
207 }
208 }
209 const data = await executeMutation()
210​
211 // Notify cache callback
212 this.mutationCache.config.onSuccess?.(
213 data,
214 this.state.variables,
215 this.state.context,
216 this as Mutation<unknown, unknown, unknown, unknown>,
217 )
218​
219 await this.options.onSuccess?.(
220 data,
221 this.state.variables!,
222 this.state.context!,
223 )
224​
225 await this.options.onSettled?.(
226 data,
227 null,
228 this.state.variables!,
229 this.state.context,
230 )
231​
232 this.dispatch({ type: 'success', data })
233 return data
234 } catch (error) {
235 try {
236 // Notify cache callback
237 this.mutationCache.config.onError?.(
238 error,
239 this.state.variables,
240 this.state.context,
241 this as Mutation<unknown, unknown, unknown, unknown>,
242 )
243​
244 if (process.env.NODE_ENV !== 'production') {
245 this.logger.error(error)
246 }
247​
248 await this.options.onError?.(
249 error as TError,
250 this.state.variables!,
251 this.state.context,
252 )
253​
254 await this.options.onSettled?.(
255 undefined,
256 error as TError,
257 this.state.variables!,
258 this.state.context,
259 )
260 throw error
261 } finally {
262 this.dispatch({ type: 'error', error: error as TError })
263 }
264 }
265 }
266​
267 private dispatch(action: Action<TData, TError, TVariables, TContext>): void {
268 const reducer = (
269 state: MutationState<TData, TError, TVariables, TContext>,
270 ): MutationState<TData, TError, TVariables, TContext> => {
271 switch (action.type) {
272 case 'failed':
273 return {
274 ...state,
275 failureCount: state.failureCount + 1,
276 }
277 case 'pause':
278 return {
279 ...state,
280 isPaused: true,
281 }
282 case 'continue':
283 return {
284 ...state,
285 isPaused: false,
286 }
287 case 'loading':
288 return {
289 ...state,
290 context: action.context,
291 data: undefined,
292 error: null,
293 isPaused: !canFetch(this.options.networkMode),
294 status: 'loading',
295 variables: action.variables,
296 }
297 case 'success':
298 return {
299 ...state,
300 data: action.data,
301 error: null,
302 status: 'success',
303 isPaused: false,
304 }
305 case 'error':
306 return {
307 ...state,
308 data: undefined,
309 error: action.error,
310 failureCount: state.failureCount + 1,
311 isPaused: false,
312 status: 'error',
313 }
314 case 'setState':
315 return {
316 ...state,
317 ...action.state,
318 }
319 }
320 }
321 this.state = reducer(this.state)
322​
323 notifyManager.batch(() => {
324 this.observers.forEach((observer) => {
325 observer.onMutationUpdate(action)
326 })
327 this.mutationCache.notify({
328 mutation: this,
329 type: 'updated',
330 action,
331 })
332 })
333 }
335​
336export function getDefaultState<
337 TData,
338 TError,
339 TVariables,
340 TContext,
341>(): MutationState<TData, TError, TVariables, TContext> {
342 return {
343 context: undefined,
344 data: undefined,
345 error: null,
346 failureCount: 0,
347 isPaused: false,
348 status: 'idle',
349 variables: undefined,
350 }