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