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β
28export interface InjectMutationOptions {
29 /**
30 * The `Injector` in which to create the mutation.
31 *
32 * If this is not provided, the current injection context will be used instead (via `inject`).
33 */
34 injector?: Injector
35}
36β
37/**
38 * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
39 * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
40 *
41 * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
42 * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
43 * the shared mutation definition. Callbacks defined in `injectMutationFn` fire for every mutation; per-call
44 * callbacks fire only for the latest call you've made β `mutateAsync` gives you a promise per call instead,
45 * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
46 * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
47 * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
48 * @param injectMutationFn - A function that returns mutation options. Similar to `computed` from Angular,
49 * this function runs in the reactive context, so signals read inside it drive the mutation's options.
50 * @param options - Additional configuration
51 * @returns The mutation result. Value fields are exposed as a `Signal` β read `data`/`error` by calling them
52 * (e.g. `mutation.data()`) β while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
53 * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
54 * `data` is defined.
55 *
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 */
174export function injectMutation<
175 TData = unknown,
176 TError = DefaultError,
177 TVariables = void,
178 TOnMutateResult = unknown,
179>(
180 injectMutationFn: () => CreateMutationOptions<
181 TData,
182 TError,
183 TVariables,
184 TOnMutateResult
185 >,
186 options?: InjectMutationOptions,
187): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {
188 !options?.injector && assertInInjectionContext(injectMutation)
189 const injector = options?.injector ?? inject(Injector)
190 const ngZone = injector.get(NgZone)
191 const pendingTasks = injector.get(PENDING_TASKS)
192 const queryClient = injector.get(QueryClient)
193β
194 /**
195 * computed() is used so signals can be inserted into the options
196 * making it reactive. Wrapping options in a function ensures embedded expressions
197 * are preserved and can keep being applied after signal changes
198 */
199 const optionsSignal = computed(injectMutationFn)
200β
201 const observerSignal = (() => {
202 let instance: MutationObserver<
203 TData,
204 TError,
205 TVariables,
206 TOnMutateResult
207 > | null = null
208β
209 return computed(() => {
210 return (instance ||= new MutationObserver(queryClient, optionsSignal()))
211 })
212 })()
213β
214 const mutateFnSignal = computed<
215 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
216 >(() => {
217 const observer = observerSignal()
218 return (
219 ...args: Parameters<
220 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
221 >
222 ) => {
223 observer.mutate(args[0] as TVariables, args[1]).catch(noop)
224 }
225 })
226β
227 /**
228 * Computed signal that gets result from mutation cache based on passed options
229 */
230 const resultFromInitialOptionsSignal = computed(() => {
231 const observer = observerSignal()
232 return observer.getCurrentResult()
233 })
234β
235 /**
236 * Signal that contains result set by subscriber
237 */
238 const resultFromSubscriberSignal = signal<MutationObserverResult<
239 TData,
240 TError,
241 TVariables,
242 TOnMutateResult
243 > | null>(null)
244β
245 effect(
246 () => {
247 const observer = observerSignal()
248 const observerOptions = optionsSignal()
249β
250 untracked(() => {
251 observer.setOptions(observerOptions)
252 })
253 },
254 {
255 injector,
256 },
257 )
258β
259 effect(
260 (onCleanup) => {
261 // observer.trackResult is not used as this optimization is not needed for Angular
262 const observer = observerSignal()
263 let pendingTaskRef: PendingTaskRef | null = null
264β
265 untracked(() => {
266 const unsubscribe = ngZone.runOutsideAngular(() =>
267 observer.subscribe(
268 notifyManager.batchCalls((state) => {
269 ngZone.run(() => {
270 // Track pending task when mutation is pending
271 if (state.isPending && !pendingTaskRef) {
272 pendingTaskRef = pendingTasks.add()
273 }
274β
275 // Clear pending task when mutation is no longer pending
276 if (!state.isPending && pendingTaskRef) {
277 pendingTaskRef()
278 pendingTaskRef = null
279 }
280β
281 if (
282 state.isError &&
283 shouldThrowError(observer.options.throwOnError, [state.error])
284 ) {
285 ngZone.onError.emit(state.error)
286 throw state.error
287 }
288β
289 resultFromSubscriberSignal.set(state)
290 })
291 }),
292 ),
293 )
294 onCleanup(() => {
295 // Clean up any pending task on destroy
296 if (pendingTaskRef) {
297 pendingTaskRef()
298 pendingTaskRef = null
299 }
300 unsubscribe()
301 })
302 })
303 },
304 {
305 injector,
306 },
307 )
308β
309 const resultSignal = computed(() => {
310 const resultFromSubscriber = resultFromSubscriberSignal()
311 const resultFromInitialOptions = resultFromInitialOptionsSignal()
312β
313 const result = resultFromSubscriber ?? resultFromInitialOptions
314β
315 return {
316 ...result,
317 mutate: mutateFnSignal(),
318 mutateAsync: result.mutate,
319 }
320 })
321β
322 return signalProxy(resultSignal) as CreateMutationResult<
323 TData,
324 TError,
325 TVariables,
326 TOnMutateResult
327 >
328}