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

mutationObserver.ts

306 lines8.5 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.
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 *
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 protected bindMethods(): void {
76 this.mutate = this.mutate.bind(this)
77 this.reset = this.reset.bind(this)
78 }
79​
80 /**
81 * Updates the observer's options.
82 *
83 * If the new `mutationKey` differs from the previous one (and both were
84 * defined), the observer is reset, detaching it from the mutation it was
85 * observing. Otherwise, if the currently observed mutation is still
86 * `pending`, its options are updated in place as well.
87 *
88 * @example
89 * ```ts
90 * observer.setOptions({
91 * mutationFn: (variables: { title: string }) => addPost(variables),
92 * onSuccess: (data) => console.log(data),
93 * })
94 * ```
95 */
96 setOptions(
97 options: MutationObserverOptions<
98 TData,
99 TError,
100 TVariables,
101 TOnMutateResult
102 >,
103 ) {
104 const prevOptions = this.options as
105 | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
106 | undefined
107 this.options = this.#client.defaultMutationOptions(options)
108 if (!shallowEqualObjects(this.options, prevOptions)) {
109 this.#client.getMutationCache().notify({
110 type: 'observerOptionsUpdated',
111 mutation: this.#currentMutation,
112 observer: this,
113 })
114 }
115​
116 if (
117 prevOptions?.mutationKey &&
118 this.options.mutationKey &&
119 hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)
120 ) {
121 this.reset()
122 } else if (this.#currentMutation?.state.status === 'pending') {
123 this.#currentMutation.setOptions(this.options)
124 }
125 }
126​
127 protected onSubscribe(): void {
128 if (this.listeners.size === 1 && this.#currentMutation) {
129 this.#currentMutation.addObserver(this)
130​
131 this.#updateResult()
132 }
133 }
134​
135 protected onUnsubscribe(): void {
136 if (!this.hasListeners()) {
137 this.#currentMutation?.removeObserver(this)
138 }
139 }
140​
141 /** @internal */
142 onMutationUpdate(
143 action: Action<TData, TError, TVariables, TOnMutateResult>,
144 ): void {
145 this.#updateResult()
146​
147 this.#notify(action)
148 }
149​
150 /**
151 * Returns the observer's current result, derived from the observed
152 * mutation's state (or the default, `idle` state if no mutation has been
153 * built yet, e.g. before the first `mutate()` call or after `reset()`).
154 */
155 getCurrentResult(): MutationObserverResult<
156 TData,
157 TError,
158 TVariables,
159 TOnMutateResult
160 > {
161 return this.#currentResult
162 }
163​
164 /**
165 * Detaches the observer from the mutation it is currently observing (if
166 * any) and resets the observed result back to its default, `idle` state.
167 *
168 * This does not cancel an in-flight mutation; the mutation itself keeps
169 * running to completion and its own callbacks still fire, but this
170 * observer stops reflecting its state and a subsequent `mutate()` call
171 * will build a brand new mutation.
172 *
173 * @example
174 * ```ts
175 * observer.reset()
176 * ```
177 *
178 * @see {@link MutationObserver#mutate}
179 */
180 reset(): void {
181 // reset needs to remove the observer from the mutation because there is no way to "get it back"
182 // another mutate call will yield a new mutation!
183 this.#currentMutation?.removeObserver(this)
184 this.#currentMutation = undefined
185 this.#updateResult()
186 this.#notify()
187 }
188​
189 /**
190 * Builds a new `Mutation` in the `MutationCache` using the observer's
191 * current options, detaches this observer from any previously observed
192 * mutation, attaches it to the new one, and executes it with the given
193 * variables.
194 *
195 * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
196 * invoked once the mutation settles, in addition to any callbacks defined
197 * on the observer's own options.
198 *
199 * @example
200 * ```ts
201 * await observer.mutate(
202 * { title: 'New post' },
203 * { onSuccess: (data) => console.log(data) },
204 * )
205 * ```
206 */
207 mutate(
208 variables: TVariables,
209 options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,
210 ): Promise<TData> {
211 this.#mutateOptions = options
212​
213 this.#currentMutation?.removeObserver(this)
214​
215 this.#currentMutation = this.#client
216 .getMutationCache()
217 .build(this.#client, this.options)
218​
219 this.#currentMutation.addObserver(this)
220​
221 return this.#currentMutation.execute(variables)
222 }
223​
224 #updateResult(): void {
225 const state =
226 this.#currentMutation?.state ??
227 getDefaultState<TData, TError, TVariables, TOnMutateResult>()
228​
229 this.#currentResult = {
230 ...state,
231 isPending: state.status === 'pending',
232 isSuccess: state.status === 'success',
233 isError: state.status === 'error',
234 isIdle: state.status === 'idle',
235 mutate: this.mutate,
236 reset: this.reset,
237 } as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
238 }
239​
240 #notify(action?: Action<TData, TError, TVariables, TOnMutateResult>): void {
241 notifyManager.batch(() => {
242 // First trigger the mutate callbacks
243 if (this.#mutateOptions && this.hasListeners()) {
244 const variables = this.#currentResult.variables!
245 const onMutateResult = this.#currentResult.context
246​
247 const context = {
248 client: this.#client,
249 meta: this.options.meta,
250 mutationKey: this.options.mutationKey,
251 } satisfies MutationFunctionContext
252​
253 if (action?.type === 'success') {
254 try {
255 this.#mutateOptions.onSuccess?.(
256 action.data,
257 variables,
258 onMutateResult,
259 context,
260 )
261 } catch (e) {
262 void Promise.reject(e)
263 }
264 try {
265 this.#mutateOptions.onSettled?.(
266 action.data,
267 null,
268 variables,
269 onMutateResult,
270 context,
271 )
272 } catch (e) {
273 void Promise.reject(e)
274 }
275 } else if (action?.type === 'error') {
276 try {
277 this.#mutateOptions.onError?.(
278 action.error,
279 variables,
280 onMutateResult,
281 context,
282 )
283 } catch (e) {
284 void Promise.reject(e)
285 }
286 try {
287 this.#mutateOptions.onSettled?.(
288 undefined,
289 action.error,
290 variables,
291 onMutateResult,
292 context,
293 )
294 } catch (e) {
295 void Promise.reject(e)
296 }
297 }
298 }
299​
300 // Then trigger the listeners
301 this.listeners.forEach((listener) => {
302 listener(this.#currentResult)
303 })
304 })
305 }