Open History to see the last commit
1---
2id: injectMutation
3title: injectMutation
4---
5β
6```ts
7function injectMutation<TData, TError, TVariables, TOnMutateResult>(injectMutationFn: () => CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, options?: InjectMutationOptions): CreateMutationResult<TData, TError, TVariables, TOnMutateResult>;
8```
9β
10Defined in: [packages/angular-query-experimental/src/inject-mutation.ts:172](https://github.com/TanStack/query/blob/main/packages/angular-query-experimental/src/inject-mutation.ts#L172)
11β
12Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
13`injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
14β
15## Type Parameters
16β
17### TData
18β
19`TData` = `unknown`
20β
21### TError
22β
23`TError` = `Error`
24β
25### TVariables
26β
27`TVariables` = `void`
28β
29### TOnMutateResult
30β
31`TOnMutateResult` = `unknown`
32β
33## Parameters
34β
35### injectMutationFn
36β
37() => [`CreateMutationOptions`](../interfaces/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
38β
39A function that returns mutation options. Similar to `computed` from Angular,
40this function runs in the reactive context, so signals read inside it drive the mutation's options.
41β
42<a id="injectMutationFn-properties"></a>
43β
44#### `injectMutationFn` properties
45β
46| Property | Type | Default value | Description |
47| ------ | ------ | ------ | ------ |
48| <a id="injectMutationFn-property-gctime"></a> `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. |
49| <a id="injectMutationFn-property-meta"></a> `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. |
50| <a id="injectMutationFn-property-mutationfn"></a> `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. |
51| <a id="injectMutationFn-property-mutationkey"></a> `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. |
52| <a id="injectMutationFn-property-networkmode"></a> `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. |
53| <a id="injectMutationFn-property-onerror"></a> `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. |
54| <a id="injectMutationFn-property-onmutate"></a> `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. |
55| <a id="injectMutationFn-property-onsettled"></a> `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. |
56| <a id="injectMutationFn-property-onsuccess"></a> `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. |
57| <a id="injectMutationFn-property-retry"></a> `retry?` | \| `number` \| `false` \| `true` \| ((`failureCount`: `number`, `error`: `TError`) => `boolean`) | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. |
58| <a id="injectMutationFn-property-retrydelay"></a> `retryDelay?` | `number` \| ((`failureCount`: `number`, `error`: `TError`) => `number`) | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. |
59| <a id="injectMutationFn-property-scope"></a> `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. |
60| <a id="injectMutationFn-property-throwonerror"></a> `throwOnError?` | `boolean` \| ((`error`: `TError`) => `boolean`) | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). |
61β
62### options?
63β
64[`InjectMutationOptions`](../interfaces/InjectMutationOptions.md)
65β
66Additional configuration
67β
68<a id="options-properties"></a>
69β
70#### `options` properties
71β
72| Property | Type | Description |
73| ------ | ------ | ------ |
74| <a id="options-property-injector"></a> `injector?` | `Injector` | The `Injector` in which to create the mutation. If this is not provided, the current injection context will be used instead (via `inject`). |
75β
76## Returns
77β
78[`CreateMutationResult`](../type-aliases/CreateMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
79β
80The mutation result. Value fields are exposed as a `Signal` β read `data`/`error` by calling them
81(e.g. `mutation.data()`) β while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
82unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
83`data` is defined.
84β
85## Remarks
86β
87`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
88second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
89the shared mutation definition. Callbacks defined in `injectMutationFn` fire for every mutation; per-call
90callbacks fire only for the latest call you've made β `mutateAsync` gives you a promise per call instead,
91so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
92β
93## See
94β
95[mutationOptions](mutationOptions.md) to share these options across multiple `injectMutation` call sites, or to look
96the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
97β
98## Examples
99β
100```angular-ts
101@Component({
102 selector: 'todos',
103 template: `
104 @if (addMutation.isPending()) {
105 <span>Adding todo...</span>
106 } @else if (addMutation.isError()) {
107 <div>An error occurred: {{ addMutation.error()?.message }}</div>
108 }
109 <button (click)="addMutation.mutate('Item')">Add</button>
110 `,
111})
112export class Todos {
113 readonly #queryClient = inject(QueryClient)
114β
115 readonly addMutation = injectMutation(() => ({
116 mutationFn: addTodo,
117 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
118 }))
119}
120```
121β
122Optimistic update via `onMutate`, rolling back on `onError`:
123```angular-ts
124@Component({
125 selector: 'todos',
126 template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
127})
128export class Todos {
129 readonly #queryClient = inject(QueryClient)
130β
131 readonly addMutation = injectMutation(() => ({
132 mutationFn: addTodo,
133 onMutate: async (newTodo) => {
134 await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
135 const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
136β
137 this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
138 ...(old ?? []),
139 newTodo,
140 ])
141β
142 // Passed to `onError` as `onMutateResult` if the mutation fails.
143 return { previousTodos }
144 },
145 onError: (_err, _newTodo, onMutateResult) => {
146 this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
147 },
148 onSettled: () => {
149 this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
150 },
151 }))
152}
153```
154β
155Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a promise per
156call instead, so you can wait for all of them when they succeed:
157```angular-ts
158@Component({
159 selector: 'todos',
160 template: `
161 <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
162 `,
163})
164export class Todos {
165 readonly #queryClient = inject(QueryClient)
166β
167 readonly addMutation = injectMutation(() => ({
168 mutationFn: addTodo,
169 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
170 }))
171β
172 async handleAddAll(todos: Array<string>) {
173 try {
174 await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
175 } catch (error) {
176 console.error('Failed to add todos:', error)
177 }
178 }
179}
180```
181β
182If some of the mutations above can fail independently of the others, and you want to know which ones did β
183rather than losing that information the moment the first one rejects β swap `Promise.all` for
184`Promise.allSettled`:
185```angular-ts
186@Component({
187 selector: 'todos',
188 template: `
189 <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
190 `,
191})
192export class Todos {
193 readonly #queryClient = inject(QueryClient)
194β
195 readonly addMutation = injectMutation(() => ({
196 mutationFn: addTodo,
197 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
198 }))
199β
200 async handleAddAll(todos: Array<string>) {
201 const addResults = await Promise.allSettled(
202 todos.map((todo) => this.addMutation.mutateAsync(todo)),
203 )
204β
205 addResults.forEach((addResult, index) => {
206 if (addResult.status === 'rejected') {
207 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
208 }
209 })
210 }
211}
212```