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

mutationObserver.ts

235 lines6.0 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​
23export class MutationObserver<
24 TData = unknown,
25 TError = DefaultError,
26 TVariables = void,
27 TOnMutateResult = unknown,
28> extends Subscribable<
29 MutationObserverListener<TData, TError, TVariables, TOnMutateResult>
30> {
31 options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
32​
33 #client: QueryClient
34 #currentResult: MutationObserverResult<
35 TData,
36 TError,
37 TVariables,
38 TOnMutateResult
39 > = undefined!
40 #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>
41 #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>
42​
43 constructor(
44 client: QueryClient,
45 options: MutationObserverOptions<
46 TData,
47 TError,
48 TVariables,
49 TOnMutateResult
50 >,
51 ) {
52 super()
53​
54 this.#client = client
55 this.setOptions(options)
56 this.bindMethods()
57 this.#updateResult()
58 }
59​
60 protected bindMethods(): void {
61 this.mutate = this.mutate.bind(this)
62 this.reset = this.reset.bind(this)
63 }
64​
65 setOptions(
66 options: MutationObserverOptions<
67 TData,
68 TError,
69 TVariables,
70 TOnMutateResult
71 >,
72 ) {
73 const prevOptions = this.options as
74 | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
75 | undefined
76 this.options = this.#client.defaultMutationOptions(options)
77 if (!shallowEqualObjects(this.options, prevOptions)) {
78 this.#client.getMutationCache().notify({
79 type: 'observerOptionsUpdated',
80 mutation: this.#currentMutation,
81 observer: this,
82 })
83 }
84​
85 if (
86 prevOptions?.mutationKey &&
87 this.options.mutationKey &&
88 hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)
89 ) {
90 this.reset()
91 } else if (this.#currentMutation?.state.status === 'pending') {
92 this.#currentMutation.setOptions(this.options)
93 }
94 }
95​
96 protected onSubscribe(): void {
97 if (this.listeners.size === 1 && this.#currentMutation) {
98 this.#currentMutation.addObserver(this)
99​
100 this.#updateResult()
101 }
102 }
103​
104 protected onUnsubscribe(): void {
105 if (!this.hasListeners()) {
106 this.#currentMutation?.removeObserver(this)
107 }
108 }
109​
110 onMutationUpdate(
111 action: Action<TData, TError, TVariables, TOnMutateResult>,
112 ): void {
113 this.#updateResult()
114​
115 this.#notify(action)
116 }
117​
118 getCurrentResult(): MutationObserverResult<
119 TData,
120 TError,
121 TVariables,
122 TOnMutateResult
123 > {
124 return this.#currentResult
125 }
126​
127 reset(): void {
128 // reset needs to remove the observer from the mutation because there is no way to "get it back"
129 // another mutate call will yield a new mutation!
130 this.#currentMutation?.removeObserver(this)
131 this.#currentMutation = undefined
132 this.#updateResult()
133 this.#notify()
134 }
135​
136 mutate(
137 variables: TVariables,
138 options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,
139 ): Promise<TData> {
140 this.#mutateOptions = options
141​
142 this.#currentMutation?.removeObserver(this)
143​
144 this.#currentMutation = this.#client
145 .getMutationCache()
146 .build(this.#client, this.options)
147​
148 this.#currentMutation.addObserver(this)
149​
150 return this.#currentMutation.execute(variables)
151 }
152​
153 #updateResult(): void {
154 const state =
155 this.#currentMutation?.state ??
156 getDefaultState<TData, TError, TVariables, TOnMutateResult>()
157​
158 this.#currentResult = {
159 ...state,
160 isPending: state.status === 'pending',
161 isSuccess: state.status === 'success',
162 isError: state.status === 'error',
163 isIdle: state.status === 'idle',
164 mutate: this.mutate,
165 reset: this.reset,
166 } as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
167 }
168​
169 #notify(action?: Action<TData, TError, TVariables, TOnMutateResult>): void {
170 notifyManager.batch(() => {
171 // First trigger the mutate callbacks
172 if (this.#mutateOptions && this.hasListeners()) {
173 const variables = this.#currentResult.variables!
174 const onMutateResult = this.#currentResult.context
175​
176 const context = {
177 client: this.#client,
178 meta: this.options.meta,
179 mutationKey: this.options.mutationKey,
180 } satisfies MutationFunctionContext
181​
182 if (action?.type === 'success') {
183 try {
184 this.#mutateOptions.onSuccess?.(
185 action.data,
186 variables,
187 onMutateResult,
188 context,
189 )
190 } catch (e) {
191 void Promise.reject(e)
192 }
193 try {
194 this.#mutateOptions.onSettled?.(
195 action.data,
196 null,
197 variables,
198 onMutateResult,
199 context,
200 )
201 } catch (e) {
202 void Promise.reject(e)
203 }
204 } else if (action?.type === 'error') {
205 try {
206 this.#mutateOptions.onError?.(
207 action.error,
208 variables,
209 onMutateResult,
210 context,
211 )
212 } catch (e) {
213 void Promise.reject(e)
214 }
215 try {
216 this.#mutateOptions.onSettled?.(
217 undefined,
218 action.error,
219 variables,
220 onMutateResult,
221 context,
222 )
223 } catch (e) {
224 void Promise.reject(e)
225 }
226 }
227 }
228​
229 // Then trigger the listeners
230 this.listeners.forEach((listener) => {
231 listener(this.#currentResult)
232 })
233 })
234 }