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 { 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 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 if (this.#mutateOptions && this.hasListeners()) {
254 const variables = this.#currentResult.variables!
255 const onMutateResult = this.#currentResult.context
256β
257 const context = {
258 client: this.#client,
259 meta: this.options.meta,
260 mutationKey: this.options.mutationKey,
261 } satisfies MutationFunctionContext
262β
263 if (action?.type === 'success') {
264 try {
265 this.#mutateOptions.onSuccess?.(
266 action.data,
267 variables,
268 onMutateResult,
269 context,
270 )
271 } catch (e) {
272 void Promise.reject(e)
273 }
274 try {
275 this.#mutateOptions.onSettled?.(
276 action.data,
277 null,
278 variables,
279 onMutateResult,
280 context,
281 )
282 } catch (e) {
283 void Promise.reject(e)
284 }
285 } else if (action?.type === 'error') {
286 try {
287 this.#mutateOptions.onError?.(
288 action.error,
289 variables,
290 onMutateResult,
291 context,
292 )
293 } catch (e) {
294 void Promise.reject(e)
295 }
296 try {
297 this.#mutateOptions.onSettled?.(
298 undefined,
299 action.error,
300 variables,
301 onMutateResult,
302 context,
303 )
304 } catch (e) {
305 void Promise.reject(e)
306 }
307 }
308 }
309β
310 // Then trigger the listeners
311 this.listeners.forEach((listener) => {
312 listener(this.#currentResult)
313 })
314 })
315 }
316}