Open History to see the last commit
1import {
2 Injector,
3 NgZone,
4 assertInInjectionContext,
5 computed,
6 effect,
7 inject,
8 signal,
9 untracked,
10} from '@angular/core'
11import {
12 MutationObserver,
13 QueryClient,
14 noop,
15 notifyManager,
16 shouldThrowError,
17} from '@tanstack/query-core'
18import { signalProxy } from './signal-proxy'
19import { PENDING_TASKS } from './pending-tasks-compat'
20import type { PendingTaskRef } from './pending-tasks-compat'
21import type { DefaultError, MutationObserverResult } from '@tanstack/query-core'
22import type {
23 CreateMutateFunction,
24 CreateMutationOptions,
25 CreateMutationResult,
26} from './types'
27β
28/**
29 * Options for `injectMutation`, passed after the function that returns the
30 * mutation options.
31 */
32export interface InjectMutationOptions {
33 /**
34 * The `Injector` in which to create the mutation.
35 *
36 * If this is not provided, the current injection context will be used instead
37 * (via `inject`).
38 */
39 injector?: Injector
40}
41β
42/**
43 * Unlike queries, mutations are typically used to create/update/delete data or
44 * perform server side-effects. `injectMutation` is the function for that.
45 * Unlike queries, mutations are not run automatically.
46 *
47 * @remarks
48 * `mutate`/`mutateAsync` also accept per-call
49 * `onSuccess`/`onError`/`onSettled` callbacks as a second argument, useful
50 * for triggering call-site side effects (e.g. navigation) without coupling
51 * them to the shared mutation definition. Callbacks defined in
52 * `injectMutationFn` fire for every mutation; per-call callbacks fire only
53 * for the latest call you've made β `mutateAsync` gives you a promise per
54 * call instead, so you can await `Promise.all`/`Promise.allSettled` over
55 * several calls and see each one's outcome.
56 * @example
57 * ```angular-ts
58 * @Component({
59 * selector: 'todos',
60 * template: `
61 * @if (addMutation.isPending()) {
62 * <span>Adding todo...</span>
63 * } @else if (addMutation.isError()) {
64 * <div>An error occurred: {{ addMutation.error()?.message }}</div>
65 * }
66 * <button (click)="addMutation.mutate('Item')">Add</button>
67 * `,
68 * })
69 * export class Todos {
70 * readonly #queryClient = inject(QueryClient)
71 *
72 * readonly addMutation = injectMutation(() => ({
73 * mutationFn: addTodo,
74 * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
75 * }))
76 * }
77 * ```
78 *
79 * @example
80 * Optimistic update via `onMutate`, rolling back on `onError`:
81 * ```angular-ts
82 * @Component({
83 * selector: 'todos',
84 * template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
85 * })
86 * export class Todos {
87 * readonly #queryClient = inject(QueryClient)
88 *
89 * readonly addMutation = injectMutation(() => ({
90 * mutationFn: addTodo,
91 * onMutate: async (newTodo) => {
92 * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
93 * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
94 *
95 * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
96 * ...(old ?? []),
97 * newTodo,
98 * ])
99 *
100 * // Passed to `onError` as `onMutateResult` if the mutation fails.
101 * return { previousTodos }
102 * },
103 * onError: (_err, _newTodo, onMutateResult) => {
104 * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
105 * },
106 * onSettled: () => {
107 * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
108 * },
109 * }))
110 * }
111 * ```
112 *
113 * @example
114 * Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a promise per
115 * call instead, so you can wait for all of them when they succeed:
116 * ```angular-ts
117 * @Component({
118 * selector: 'todos',
119 * template: `
120 * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
121 * `,
122 * })
123 * export class Todos {
124 * readonly #queryClient = inject(QueryClient)
125 *
126 * readonly addMutation = injectMutation(() => ({
127 * mutationFn: addTodo,
128 * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
129 * }))
130 *
131 * async handleAddAll(todos: Array<string>) {
132 * try {
133 * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
134 * } catch (error) {
135 * console.error('Failed to add todos:', error)
136 * }
137 * }
138 * }
139 * ```
140 *
141 * @example
142 * If some of the mutations above can fail independently of the others, and you want to know which ones did β
143 * rather than losing that information the moment the first one rejects β swap `Promise.all` for
144 * `Promise.allSettled`:
145 * ```angular-ts
146 * @Component({
147 * selector: 'todos',
148 * template: `
149 * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
150 * `,
151 * })
152 * export class Todos {
153 * readonly #queryClient = inject(QueryClient)
154 *
155 * readonly addMutation = injectMutation(() => ({
156 * mutationFn: addTodo,
157 * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
158 * }))
159 *
160 * async handleAddAll(todos: Array<string>) {
161 * const addResults = await Promise.allSettled(
162 * todos.map((todo) => this.addMutation.mutateAsync(todo)),
163 * )
164 *
165 * addResults.forEach((addResult, index) => {
166 * if (addResult.status === 'rejected') {
167 * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
168 * }
169 * })
170 * }
171 * }
172 * ```
173 *
174 * @param injectMutationFn - A function that returns mutation options. Similar
175 * to `computed` from Angular, this function runs in the reactive context, so
176 * signals read inside it drive the mutation's options.
177 * @param options - Additional configuration
178 * @returns The mutation result. Value fields are exposed as a `Signal` β read
179 * `data`/`error` by calling them (e.g. `mutation.data()`) β while function
180 * fields (`mutate`, `mutateAsync`, `reset`) are called directly, unchanged.
181 * `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can
182 * call to narrow whether `data` is defined.
183 * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
184 * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
185 */
186export function injectMutation<
187 TData = unknown,
188 TError = DefaultError,
189 TVariables = void,
190 TOnMutateResult = unknown,
191>(
192 injectMutationFn: () => CreateMutationOptions<
193 TData,
194 TError,
195 TVariables,
196 TOnMutateResult
197 >,
198 options?: InjectMutationOptions,
199): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {
200 !options?.injector && assertInInjectionContext(injectMutation)
201 const injector = options?.injector ?? inject(Injector)
202 const ngZone = injector.get(NgZone)
203 const pendingTasks = injector.get(PENDING_TASKS)
204 const queryClient = injector.get(QueryClient)
205β
206 /**
207 * Computed() is used so signals can be inserted into the options making it
208 * reactive. Wrapping options in a function ensures embedded expressions are
209 * preserved and can keep being applied after signal changes
210 */
211 const optionsSignal = computed(injectMutationFn)
212β
213 const observerSignal = (() => {
214 let instance: MutationObserver<
215 TData,
216 TError,
217 TVariables,
218 TOnMutateResult
219 > | null = null
220β
221 return computed(() => {
222 return (instance ||= new MutationObserver(queryClient, optionsSignal()))
223 })
224 })()
225β
226 const mutateFnSignal = computed<
227 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
228 >(() => {
229 const observer = observerSignal()
230 return (
231 ...args: Parameters<
232 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
233 >
234 ) => {
235 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
236 }
237 })
238β
239 /**
240 * Computed signal that gets result from mutation cache based on passed
241 * options
242 */
243 const resultFromInitialOptionsSignal = computed(() => {
244 const observer = observerSignal()
245 return observer.getCurrentResult()
246 })
247β
248 /** Signal that contains result set by subscriber */
249 const resultFromSubscriberSignal = signal<MutationObserverResult<
250 TData,
251 TError,
252 TVariables,
253 TOnMutateResult
254 > | null>(null)
255β
256 effect(
257 () => {
258 const observer = observerSignal()
259 const observerOptions = optionsSignal()
260β
261 untracked(() => {
262 observer.setOptions(observerOptions)
263 })
264 },
265 {
266 injector,
267 },
268 )
269β
270 effect(
271 (onCleanup) => {
272 // observer.trackResult is not used as this optimization is not needed for Angular
273 const observer = observerSignal()
274 let pendingTaskRef: PendingTaskRef | null = null
275β
276 untracked(() => {
277 const unsubscribe = ngZone.runOutsideAngular(() =>
278 observer.subscribe(
279 notifyManager.batchCalls((state) => {
280 ngZone.run(() => {
281 // Track pending task when mutation is pending
282 if (state.isPending && !pendingTaskRef) {
283 pendingTaskRef = pendingTasks.add()
284 }
285β
286 // Clear pending task when mutation is no longer pending
287 if (!state.isPending && pendingTaskRef) {
288 pendingTaskRef()
289 pendingTaskRef = null
290 }
291β
292 if (
293 state.isError &&
294 shouldThrowError(observer.options.throwOnError, [state.error])
295 ) {
296 ngZone.onError.emit(state.error)
297 throw state.error
298 }
299β
300 resultFromSubscriberSignal.set(state)
301 })
302 }),
303 ),
304 )
305 onCleanup(() => {
306 // Clean up any pending task on destroy
307 if (pendingTaskRef) {
308 pendingTaskRef()
309 pendingTaskRef = null
310 }
311 unsubscribe()
312 })
313 })
314 },
315 {
316 injector,
317 },
318 )
319β
320 const resultSignal = computed(() => {
321 const resultFromSubscriber = resultFromSubscriberSignal()
322 const resultFromInitialOptions = resultFromInitialOptionsSignal()
323β
324 const result = resultFromSubscriber ?? resultFromInitialOptions
325β
326 return {
327 ...result,
328 mutate: mutateFnSignal(),
329 mutateAsync: result.mutate,
330 }
331 })
332β
333 return signalProxy(resultSignal) as CreateMutationResult<
334 TData,
335 TError,
336 TVariables,
337 TOnMutateResult
338 >
339}