Open History to see the last commit
1import { getDefaultState } from './mutation'
2import { notifyManager } from './notifyManager'
3import { Subscribable } from './subscribable'
4import { hashKey, shallowEqualObjects } from './utils'
5import type { Action, Mutation } from './mutation'
6import type { QueryClient } from './queryClient'
7import type {
8 DefaultError,
9 MutateOptions,
10 MutationFunctionContext,
11 MutationObserverOptions,
12 MutationObserverResult,
13} from './types'
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 hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)
124 ) {
125 this.reset()
126 } else if (this.#currentMutation?.state.status === 'pending') {
127 this.#currentMutation.setOptions(this.options)
128 }
129 }
130β
131 protected override onSubscribe(): void {
132 if (this.listeners.size === 1 && this.#currentMutation) {
133 this.#currentMutation.addObserver(this)
134β
135 this.#updateResult()
136 }
137 }
138β
139 protected override onUnsubscribe(): void {
140 if (!this.hasListeners()) {
141 this.#currentMutation?.removeObserver(this)
142 }
143 }
144β
145 /**
146 * Updates the observer's result when the observed mutation changes, and notifies its listeners.
147 * @internal
148 * @param action - The action that updated the observed mutation, passed on to the observer's
149 * callbacks.
150 */
151 onMutationUpdate(
152 action: Action<TData, TError, TVariables, TOnMutateResult>,
153 ): void {
154 this.#updateResult()
155β
156 this.#notify(action)
157 }
158β
159 /**
160 * Returns the observer's current result, derived from the observed
161 * mutation's state (or the default, `idle` state if no mutation has been
162 * built yet, e.g. before the first `mutate()` call or after `reset()`).
163 * @returns The observer's latest result.
164 */
165 getCurrentResult(): MutationObserverResult<
166 TData,
167 TError,
168 TVariables,
169 TOnMutateResult
170 > {
171 return this.#currentResult
172 }
173β
174 /**
175 * Detaches the observer from the mutation it is currently observing (if
176 * any) and resets the observed result back to its default, `idle` state.
177 *
178 * This does not cancel an in-flight mutation; the mutation itself keeps
179 * running to completion and its own callbacks still fire, but this
180 * observer stops reflecting its state and a subsequent `mutate()` call
181 * will build a brand new mutation.
182 * @see {@link MutationObserver#mutate}
183 * @example
184 * ```ts
185 * observer.reset()
186 * ```
187 */
188 reset(): void {
189 // reset needs to remove the observer from the mutation because there is no way to "get it back"
190 // another mutate call will yield a new mutation!
191 this.#currentMutation?.removeObserver(this)
192 this.#currentMutation = undefined
193 this.#updateResult()
194 this.#notify()
195 }
196β
197 /**
198 * Builds a new `Mutation` in the `MutationCache` using the observer's
199 * current options, detaches this observer from any previously observed
200 * mutation, attaches it to the new one, and executes it with the given
201 * variables.
202 *
203 * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
204 * invoked once the mutation settles, in addition to any callbacks defined
205 * on the observer's own options.
206 * @param variables - The variables passed to the `mutationFn`.
207 * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.
208 * @returns A promise that resolves with the mutation's data, or rejects with its error.
209 * @example
210 * ```ts
211 * await observer.mutate(
212 * { title: 'New post' },
213 * { onSuccess: (data) => console.log(data) },
214 * )
215 * ```
216 */
217 mutate(
218 variables: TVariables,
219 options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,
220 ): Promise<TData> {
221 this.#mutateOptions = options
222β
223 this.#currentMutation?.removeObserver(this)
224β
225 this.#currentMutation = this.#client
226 .getMutationCache()
227 .build(this.#client, this.options)
228β
229 this.#currentMutation.addObserver(this)
230β
231 return this.#currentMutation.execute(variables)
232 }
233β
234 #updateResult(): void {
235 const state =
236 this.#currentMutation?.state ??
237 getDefaultState<TData, TError, TVariables, TOnMutateResult>()
238β
239 this.#currentResult = {
240 ...state,
241 isPending: state.status === 'pending',
242 isSuccess: state.status === 'success',
243 isError: state.status === 'error',
244 isIdle: state.status === 'idle',
245 mutate: this.mutate,
246 reset: this.reset,
247 } as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
248 }
249β
250 #notify(action?: Action<TData, TError, TVariables, TOnMutateResult>): void {
251 notifyManager.batch(() => {
252 // First trigger the mutate callbacks
253 // Snapshot mutateOptions before dispatching β a callback (e.g. onSuccess)
254 // may call mutate() again, which overwrites this.#mutateOptions in place.
255 // Without the snapshot, onSettled would fire with the *next* mutation's
256 // options but the *current* mutation's data/variables.
257 const mutateOptions = this.#mutateOptions
258 if (mutateOptions && this.hasListeners()) {
259 const variables = this.#currentResult.variables!
260 const onMutateResult = this.#currentResult.context
261β
262 const context = {
263 client: this.#client,
264 meta: this.options.meta,
265 mutationKey: this.options.mutationKey,
266 } satisfies MutationFunctionContext
267β
268 if (action?.type === 'success') {
269 try {
270 mutateOptions.onSuccess?.(
271 action.data,
272 variables,
273 onMutateResult,
274 context,
275 )
276 } catch (e) {
277 void Promise.reject(e)
278 }
279 try {
280 mutateOptions.onSettled?.(
281 action.data,
282 null,
283 variables,
284 onMutateResult,
285 context,
286 )
287 } catch (e) {
288 void Promise.reject(e)
289 }
290 } else if (action?.type === 'error') {
291 try {
292 mutateOptions.onError?.(
293 action.error,
294 variables,
295 onMutateResult,
296 context,
297 )
298 } catch (e) {
299 void Promise.reject(e)
300 }
301 try {
302 mutateOptions.onSettled?.(
303 undefined,
304 action.error,
305 variables,
306 onMutateResult,
307 context,
308 )
309 } catch (e) {
310 void Promise.reject(e)
311 }
312 }
313 }
314β
315 // Then trigger the listeners
316 this.listeners.forEach((listener) => {
317 listener(this.#currentResult)
318 })
319 })
320 }
321}