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

inject-mutation.ts

256 lines8.4 KB

1import {
2 assertInInjectionContext,
3 computed,
4 effect,
5 inject,
6 untracked,
7} from '@angular/core'
8import { MutationObserver, QueryClient, noop } from '@tanstack/query-core'
9import { injectExternalStore } from './utils/inject-external-store'
10import { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'
11import { injectQueryZone } from './utils/inject-query-zone'
12import { mutationResultFields } from './utils/result-fields'
13import { signalProxy } from './utils/signal-proxy'
14import type { DefaultError } from '@tanstack/query-core'
15import type {
16 CreateMutateAsyncFunction,
17 CreateMutateFunction,
18 CreateMutationOptions,
19 CreateMutationResult,
20} from './types'
21​
22/**
23 * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
24 * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
25 * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this
26 * function runs in the reactive context, so signals read inside it drive the mutation's options.
27 * @returns The mutation result. Value fields are exposed as a `Signal` β€” read `data`/`error` by calling them
28 * (e.g. `mutation.data()`) β€” while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
29 * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
30 * `data` is defined.
31 * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
32 * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
33 * the shared mutation definition. Callbacks defined in `optionsFn` fire for every mutation; per-call
34 * callbacks fire only for the latest call you've made β€” `mutateAsync` gives you a promise per call instead,
35 * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
36 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations
37 * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
38 * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
39 * @example
40 * ```angular-ts
41 * @Component({
42 * selector: 'todos',
43 * template: `
44 * @if (addMutation.isPending()) {
45 * <span>Adding todo...</span>
46 * } @else if (addMutation.isError()) {
47 * <div>An error occurred: {{ addMutation.error()?.message }}</div>
48 * }
49 * <button (click)="addMutation.mutate('Item')">Add</button>
50 * `,
51 * })
52 * export class Todos {
53 * readonly #queryClient = inject(QueryClient)
54 *
55 * readonly addMutation = injectMutation(() => ({
56 * mutationFn: addTodo,
57 * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
58 * }))
59 * }
60 * ```
61 * @example
62 * Optimistic update via `onMutate`, rolling back on `onError`:
63 * ```angular-ts
64 * @Component({
65 * selector: 'todos',
66 * template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
67 * })
68 * export class Todos {
69 * readonly #queryClient = inject(QueryClient)
70 *
71 * readonly addMutation = injectMutation(() => ({
72 * mutationFn: addTodo,
73 * onMutate: async (newTodo) => {
74 * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
75 * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
76 *
77 * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
78 * ...(old ?? []),
79 * newTodo,
80 * ])
81 *
82 * // Passed to `onError` as `onMutateResult` if the mutation fails.
83 * return { previousTodos }
84 * },
85 * onError: (_err, _newTodo, onMutateResult) => {
86 * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
87 * },
88 * onSettled: () => {
89 * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
90 * },
91 * }))
92 * }
93 * ```
94 * @example
95 * Callbacks passed per call to `mutate` only fire for the last call β€” `mutateAsync` gives you a promise per
96 * call instead, so you can wait for all of them when they succeed:
97 * ```angular-ts
98 * @Component({
99 * selector: 'todos',
100 * template: `
101 * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
102 * `,
103 * })
104 * export class Todos {
105 * readonly #queryClient = inject(QueryClient)
106 *
107 * readonly addMutation = injectMutation(() => ({
108 * mutationFn: addTodo,
109 * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
110 * }))
111 *
112 * async handleAddAll(todos: Array<string>) {
113 * try {
114 * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
115 * } catch (error) {
116 * console.error('Failed to add todos:', error)
117 * }
118 * }
119 * }
120 * ```
121 * @example
122 * If some of the mutations above can fail independently of the others, and you want to know which ones did β€”
123 * rather than losing that information the moment the first one rejects β€” swap `Promise.all` for
124 * `Promise.allSettled`:
125 * ```angular-ts
126 * @Component({
127 * selector: 'todos',
128 * template: `
129 * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
130 * `,
131 * })
132 * export class Todos {
133 * readonly #queryClient = inject(QueryClient)
134 *
135 * readonly addMutation = injectMutation(() => ({
136 * mutationFn: addTodo,
137 * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
138 * }))
139 *
140 * async handleAddAll(todos: Array<string>) {
141 * const addResults = await Promise.allSettled(
142 * todos.map((todo) => this.addMutation.mutateAsync(todo)),
143 * )
144 *
145 * addResults.forEach((addResult, index) => {
146 * if (addResult.status === 'rejected') {
147 * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
148 * }
149 * })
150 * }
151 * }
152 * ```
153 */
154export function injectMutation<
155 TData = unknown,
156 TError = DefaultError,
157 TVariables = void,
158 TOnMutateResult = unknown,
159>(
160 optionsFn: () => CreateMutationOptions<
161 TData,
162 TError,
163 TVariables,
164 TOnMutateResult
165 >,
166): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {
167 if (typeof ngDevMode === 'undefined' || ngDevMode) {
168 assertInInjectionContext(injectMutation)
169 }
170 const outsideZone = injectQueryZone()
171 const queryClient = inject(QueryClient)
172 const lifecycle = injectPendingTasksLifecycle()
173​
174 const optionsSignal = computed(optionsFn)
175​
176 const observerSignal = computed(
177 () => new MutationObserver(queryClient, untracked(optionsSignal)),
178 )
179​
180 // Configure the observer outside the result computation. Mutation-cache
181 // listeners can synchronously read the public result while setOptions emits.
182 effect(() => {
183 const options = optionsSignal()
184 outsideZone(() => untracked(() => observerSignal().setOptions(options)))
185 })
186​
187 const mutationStateSignal = injectExternalStore(() => {
188 const observer = observerSignal()
189 return {
190 getSnapshot: () => observer.getCurrentResult(),
191 subscribe: (onStoreChange) => observer.subscribe(onStoreChange),
192 }
193 })
194​
195 const mutate: CreateMutateFunction<
196 TData,
197 TError,
198 TVariables,
199 TOnMutateResult
200 > = (...args) => {
201 mutateAsync(...args).catch(noop)
202 }
203​
204 let pendingInvocations = 0
205​
206 const mutateAsync: CreateMutateAsyncFunction<
207 TData,
208 TError,
209 TVariables,
210 TOnMutateResult
211 > = (...args) => {
212 return outsideZone(() =>
213 untracked(() => {
214 const observer = observerSignal()
215 observer.setOptions(optionsSignal())
216 pendingInvocations++
217 lifecycle.setPending(true)
218 // Track invocations, not the observer's latest result: reset or a later
219 // mutation completing must not release work which is still running.
220 const settled = () => {
221 pendingInvocations--
222 lifecycle.setPending(pendingInvocations > 0)
223 }
224 try {
225 return observer
226 .mutate(args[0] as TVariables, args[1])
227 .finally(settled)
228 } catch (error) {
229 settled()
230 throw error
231 }
232 }),
233 )
234 }
235​
236 const reset = () => {
237 outsideZone(() =>
238 untracked(() => {
239 const observer = observerSignal()
240 observer.setOptions(optionsSignal())
241 observer.reset()
242 }),
243 )
244 }
245​
246 return Object.assign(signalProxy(mutationStateSignal, mutationResultFields), {
247 mutate,
248 mutateAsync,
249 reset,
250 }) as unknown as CreateMutationResult<
251 TData,
252 TError,
253 TVariables,
254 TOnMutateResult
255 >