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

mutationObserver.ts

170 lines4.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 MutationObserverOptions,
10 MutationObserverResult,
11} from './types'
12import type { Action, Mutation } from './mutation'
13​
14// TYPES
15​
16type MutationObserverListener<TData, TError, TVariables, TContext> = (
17 result: MutationObserverResult<TData, TError, TVariables, TContext>,
18) => void
19​
20// CLASS
21​
22export class MutationObserver<
23 TData = unknown,
24 TError = DefaultError,
25 TVariables = void,
26 TContext = unknown,
27> extends Subscribable<
28 MutationObserverListener<TData, TError, TVariables, TContext>
29> {
30 options!: MutationObserverOptions<TData, TError, TVariables, TContext>
31​
32 #client: QueryClient
33 #currentResult: MutationObserverResult<TData, TError, TVariables, TContext> =
34 undefined!
35 #currentMutation?: Mutation<TData, TError, TVariables, TContext>
36 #mutateOptions?: MutateOptions<TData, TError, TVariables, TContext>
37​
38 constructor(
39 client: QueryClient,
40 options: MutationObserverOptions<TData, TError, TVariables, TContext>,
41 ) {
42 super()
43​
44 this.#client = client
45 this.setOptions(options)
46 this.bindMethods()
47 this.#updateResult()
48 }
49​
50 protected bindMethods(): void {
51 this.mutate = this.mutate.bind(this)
52 this.reset = this.reset.bind(this)
53 }
54​
55 setOptions(
56 options: MutationObserverOptions<TData, TError, TVariables, TContext>,
57 ) {
58 const prevOptions = this.options as
59 | MutationObserverOptions<TData, TError, TVariables, TContext>
60 | undefined
61 this.options = this.#client.defaultMutationOptions(options)
62 if (!shallowEqualObjects(prevOptions, this.options)) {
63 this.#client.getMutationCache().notify({
64 type: 'observerOptionsUpdated',
65 mutation: this.#currentMutation,
66 observer: this,
67 })
68 }
69 this.#currentMutation?.setOptions(this.options)
70​
71 if (
72 prevOptions?.mutationKey &&
73 this.options.mutationKey &&
74 hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)
75 ) {
76 this.reset()
77 }
78 }
79​
80 protected onUnsubscribe(): void {
81 if (!this.hasListeners()) {
82 this.#currentMutation?.removeObserver(this)
83 }
84 }
85​
86 onMutationUpdate(action: Action<TData, TError, TVariables, TContext>): void {
87 this.#updateResult()
88​
89 this.#notify(action)
90 }
91​
92 getCurrentResult(): MutationObserverResult<
93 TData,
94 TError,
95 TVariables,
96 TContext
97 > {
98 return this.#currentResult
99 }
100​
101 reset(): void {
102 // reset needs to remove the observer from the mutation because there is no way to "get it back"
103 // another mutate call will yield a new mutation!
104 this.#currentMutation?.removeObserver(this)
105 this.#currentMutation = undefined
106 this.#updateResult()
107 this.#notify()
108 }
109​
110 mutate(
111 variables: TVariables,
112 options?: MutateOptions<TData, TError, TVariables, TContext>,
113 ): Promise<TData> {
114 this.#mutateOptions = options
115​
116 this.#currentMutation?.removeObserver(this)
117​
118 this.#currentMutation = this.#client
119 .getMutationCache()
120 .build(this.#client, this.options)
121​
122 this.#currentMutation.addObserver(this)
123​
124 return this.#currentMutation.execute(variables)
125 }
126​
127 #updateResult(): void {
128 const state =
129 this.#currentMutation?.state ??
130 getDefaultState<TData, TError, TVariables, TContext>()
131​
132 this.#currentResult = {
133 ...state,
134 isPending: state.status === 'pending',
135 isSuccess: state.status === 'success',
136 isError: state.status === 'error',
137 isIdle: state.status === 'idle',
138 mutate: this.mutate,
139 reset: this.reset,
140 } as MutationObserverResult<TData, TError, TVariables, TContext>
141 }
142​
143 #notify(action?: Action<TData, TError, TVariables, TContext>): void {
144 notifyManager.batch(() => {
145 // First trigger the mutate callbacks
146 if (this.#mutateOptions && this.hasListeners()) {
147 const variables = this.#currentResult.variables!
148 const context = this.#currentResult.context
149​
150 if (action?.type === 'success') {
151 this.#mutateOptions.onSuccess?.(action.data, variables, context!)
152 this.#mutateOptions.onSettled?.(action.data, null, variables, context)
153 } else if (action?.type === 'error') {
154 this.#mutateOptions.onError?.(action.error, variables, context)
155 this.#mutateOptions.onSettled?.(
156 undefined,
157 action.error,
158 variables,
159 context,
160 )
161 }
162 }
163​
164 // Then trigger the listeners
165 this.listeners.forEach((listener) => {
166 listener(this.#currentResult)
167 })
168 })
169 }