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

mutationObserver.ts

328 lines9.8 KB

1import { getDefaultState } from './mutation'
2import { notifyManager } from './notifyManager'
3import { Subscribable } from './subscribable'
4import { hashKeyByOptions, shallowEqualObjects } from './utils'
5import type { QueryClient } from './queryClient'
6import type {
7 DefaultError,
8 MutateOptions,
9 MutationFunctionContext,
10 MutationObserverOptions,
11 MutationObserverResult,
12} from './types'
13import type { Action, Mutation } from './mutation'
14​
15// TYPES
16​
17type MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (
18 result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,
19) => void
20​
21// CLASS
22​
23/**
24 * Observes a single mutation and derives a `MutationObserverResult` from it.
25 * A framework hook like `useMutation` creates one `MutationObserver` per hook
26 * call, keeps it stable across re-renders, calls `setOptions` when the options
27 * passed to the hook change, subscribes to it to re-render on updates, and
28 * reads `getCurrentResult()` for the value to return. Calling `mutate()`
29 * builds a new underlying `Mutation` in the `MutationCache` and executes it.
30 * @example
31 * ```ts
32 * const observer = new MutationObserver(queryClient, {
33 * mutationFn: (variables: { title: string }) => addPost(variables),
34 * })
35 * ```
36 */
37export class MutationObserver<
38 TData = unknown,
39 TError = DefaultError,
40 TVariables = void,
41 TOnMutateResult = unknown,
42> extends Subscribable<
43 MutationObserverListener<TData, TError, TVariables, TOnMutateResult>
44> {
45 options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
46​
47 #client: QueryClient
48 #currentResult: MutationObserverResult<
49 TData,
50 TError,
51 TVariables,
52 TOnMutateResult
53 > = undefined!
54 #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>
55 #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>
56​
57 constructor(
58 client: QueryClient,
59 options: MutationObserverOptions<
60 TData,
61 TError,
62 TVariables,
63 TOnMutateResult
64 >,
65 ) {
66 super()
67​
68 this.#client = client
69 this.setOptions(options)
70 this.bindMethods()
71 this.#updateResult()
72 }
73​
74 /**
75 * Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when
76 * destructured from it.
77 */
78 protected bindMethods(): void {
79 this.mutate = this.mutate.bind(this)
80 this.reset = this.reset.bind(this)
81 }
82​
83 /**
84 * Updates the observer's options.
85 *
86 * If the new `mutationKey` differs from the previous one (and both were
87 * defined), the observer is reset, detaching it from the mutation it was
88 * observing. Otherwise, if the currently observed mutation is still
89 * `pending`, its options are updated in place as well.
90 * @param options - The new mutation observer options. They are defaulted with {@link
91 * QueryClient#defaultMutationOptions} before being applied.
92 * @example
93 * ```ts
94 * observer.setOptions({
95 * mutationFn: (variables: { title: string }) => addPost(variables),
96 * onSuccess: (data) => console.log(data),
97 * })
98 * ```
99 */
100 setOptions(
101 options: MutationObserverOptions<
102 TData,
103 TError,
104 TVariables,
105 TOnMutateResult
106 >,
107 ) {
108 const prevOptions = this.options as
109 | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
110 | undefined
111 this.options = this.#client.defaultMutationOptions(options)
112 if (!shallowEqualObjects(this.options, prevOptions)) {
113 this.#client.getMutationCache().notify({
114 type: 'observerOptionsUpdated',
115 mutation: this.#currentMutation,
116 observer: this,
117 })
118 }
119​
120 if (
121 prevOptions?.mutationKey &&
122 this.options.mutationKey &&
123 hashKeyByOptions(
124 prevOptions.mutationKey,
125 this.#client.getMutationCache().config.mutationKey,
126 ) !==
127 hashKeyByOptions(
128 this.options.mutationKey,
129 this.#client.getMutationCache().config.mutationKey,
130 )
131 ) {
132 this.reset()
133 } else if (this.#currentMutation?.state.status === 'pending') {
134 this.#currentMutation.setOptions(this.options)
135 }
136 }
137​
138 protected override onSubscribe(): void {
139 if (this.listeners.size === 1 && this.#currentMutation) {
140 this.#currentMutation.addObserver(this)
141​
142 this.#updateResult()
143 }
144 }
145​
146 protected override onUnsubscribe(): void {
147 if (!this.hasListeners()) {
148 this.#currentMutation?.removeObserver(this)
149 }
150 }
151​
152 /**
153 * Updates the observer's result when the observed mutation changes, and notifies its listeners.
154 * @internal
155 * @param action - The action that updated the observed mutation, passed on to the observer's
156 * callbacks.
157 */
158 onMutationUpdate(
159 action: Action<TData, TError, TVariables, TOnMutateResult>,
160 ): void {
161 this.#updateResult()
162​
163 this.#notify(action)
164 }
165​
166 /**
167 * Returns the observer's current result, derived from the observed
168 * mutation's state (or the default, `idle` state if no mutation has been
169 * built yet, e.g. before the first `mutate()` call or after `reset()`).
170 * @returns The observer's latest result.
171 */
172 getCurrentResult(): MutationObserverResult<
173 TData,
174 TError,
175 TVariables,
176 TOnMutateResult
177 > {
178 return this.#currentResult
179 }
180​
181 /**
182 * Detaches the observer from the mutation it is currently observing (if
183 * any) and resets the observed result back to its default, `idle` state.
184 *
185 * This does not cancel an in-flight mutation; the mutation itself keeps
186 * running to completion and its own callbacks still fire, but this
187 * observer stops reflecting its state and a subsequent `mutate()` call
188 * will build a brand new mutation.
189 * @see {@link MutationObserver#mutate}
190 * @example
191 * ```ts
192 * observer.reset()
193 * ```
194 */
195 reset(): void {
196 // reset needs to remove the observer from the mutation because there is no way to "get it back"
197 // another mutate call will yield a new mutation!
198 this.#currentMutation?.removeObserver(this)
199 this.#currentMutation = undefined
200 this.#updateResult()
201 this.#notify()
202 }
203​
204 /**
205 * Builds a new `Mutation` in the `MutationCache` using the observer's
206 * current options, detaches this observer from any previously observed
207 * mutation, attaches it to the new one, and executes it with the given
208 * variables.
209 *
210 * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
211 * invoked once the mutation settles, in addition to any callbacks defined
212 * on the observer's own options.
213 * @param variables - The variables passed to the `mutationFn`.
214 * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.
215 * @returns A promise that resolves with the mutation's data, or rejects with its error.
216 * @example
217 * ```ts
218 * await observer.mutate(
219 * { title: 'New post' },
220 * { onSuccess: (data) => console.log(data) },
221 * )
222 * ```
223 */
224 mutate(
225 variables: TVariables,
226 options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,
227 ): Promise<TData> {
228 this.#mutateOptions = options
229​
230 this.#currentMutation?.removeObserver(this)
231​
232 this.#currentMutation = this.#client
233 .getMutationCache()
234 .build(this.#client, this.options)
235​
236 this.#currentMutation.addObserver(this)
237​
238 return this.#currentMutation.execute(variables)
239 }
240​
241 #updateResult(): void {
242 const state =
243 this.#currentMutation?.state ??
244 getDefaultState<TData, TError, TVariables, TOnMutateResult>()
245​
246 this.#currentResult = {
247 ...state,
248 isPending: state.status === 'pending',
249 isSuccess: state.status === 'success',
250 isError: state.status === 'error',
251 isIdle: state.status === 'idle',
252 mutate: this.mutate,
253 reset: this.reset,
254 } as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
255 }
256​
257 #notify(action?: Action<TData, TError, TVariables, TOnMutateResult>): void {
258 notifyManager.batch(() => {
259 // First trigger the mutate callbacks
260 // Snapshot mutateOptions before dispatching β€” a callback (e.g. onSuccess)
261 // may call mutate() again, which overwrites this.#mutateOptions in place.
262 // Without the snapshot, onSettled would fire with the *next* mutation's
263 // options but the *current* mutation's data/variables.
264 const mutateOptions = this.#mutateOptions
265 if (mutateOptions && this.hasListeners()) {
266 const variables = this.#currentResult.variables!
267 const onMutateResult = this.#currentResult.context
268​
269 const context = {
270 client: this.#client,
271 meta: this.options.meta,
272 mutationKey: this.options.mutationKey,
273 } satisfies MutationFunctionContext
274​
275 if (action?.type === 'success') {
276 try {
277 mutateOptions.onSuccess?.(
278 action.data,
279 variables,
280 onMutateResult,
281 context,
282 )
283 } catch (e) {
284 void Promise.reject(e)
285 }
286 try {
287 mutateOptions.onSettled?.(
288 action.data,
289 null,
290 variables,
291 onMutateResult,
292 context,
293 )
294 } catch (e) {
295 void Promise.reject(e)
296 }
297 } else if (action?.type === 'error') {
298 try {
299 mutateOptions.onError?.(
300 action.error,
301 variables,
302 onMutateResult,
303 context,
304 )
305 } catch (e) {
306 void Promise.reject(e)
307 }
308 try {
309 mutateOptions.onSettled?.(
310 undefined,
311 action.error,
312 variables,
313 onMutateResult,
314 context,
315 )
316 } catch (e) {
317 void Promise.reject(e)
318 }
319 }
320 }
321​
322 // Then trigger the listeners
323 this.listeners.forEach((listener) => {
324 listener(this.#currentResult)
325 })
326 })
327 }