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

mutationObserver.ts

333 lines9.7 KB

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