Open History to see the last commit
1---
2id: injectMutation
3title: injectMutation
4---
5β
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7β
8```ts
9function injectMutation<TData = unknown, TError = Error, TVariables = void, TOnMutateResult = unknown>(injectMutationFn: () => CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, options?: InjectMutationOptions): CreateMutationResult<TData, TError, TVariables, TOnMutateResult>;
10```
11β
12Defined 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)
13β
14Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
15`injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
16β
17## Type Parameters
18β
19### TData
20β
21`TData` = `unknown`
22β
23### TError
24β
25`TError` = `Error`
26β
27### TVariables
28β
29`TVariables` = `void`
30β
31### TOnMutateResult
32β
33`TOnMutateResult` = `unknown`
34β
35## Parameters
36β
37### injectMutationFn
38β
39() => [`CreateMutationOptions`](../interfaces/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
40β
41A function that returns mutation options. Similar to `computed` from Angular,
42this function runs in the reactive context, so signals read inside it drive the mutation's options.
43β
44<a id="injectMutationFn-properties"></a>
45β
46#### `injectMutationFn` properties
47β
48| Property | Type | Default value | Description |
49| ------ | ------ | ------ | ------ |
50| <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. |
51| <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`. |
52| <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. |
53| <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`. |
54| <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. |
55| <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. |
56| <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. |
57| <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. |
58| <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. |
59| <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. |
60| <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. |
61| <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. |
62| <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`). |
63β
64### options?
65β
66[`InjectMutationOptions`](../interfaces/InjectMutationOptions.md)
67β
68Additional configuration
69β
70<a id="options-properties"></a>
71β
72#### `options` properties
73β
74| Property | Type | Description |
75| ------ | ------ | ------ |
76| <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`). |
77β
78## Returns
79β
80[`CreateMutationResult`](../type-aliases/CreateMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
81β
82The mutation result. Value fields are exposed as a `Signal` β read `data`/`error` by calling them
83(e.g. `mutation.data()`) β while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
84unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
85`data` is defined.
86β
87## Remarks
88β
89`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
90second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
91the shared mutation definition. Callbacks defined in `injectMutationFn` fire for every mutation; per-call
92callbacks fire only for the latest call you've made β `mutateAsync` gives you a promise per call instead,
93so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
94β
95## See
96β
97[mutationOptions](mutationOptions.md) to share these options across multiple `injectMutation` call sites, or to look
98the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
99β
100## Examples
101β
102```angular-ts
103@Component({
104 selector: 'todos',
105 template: `
106 @if (addMutation.isPending()) {
107 <span>Adding todo...</span>
108 } @else if (addMutation.isError()) {
109 <div>An error occurred: {{ addMutation.error()?.message }}</div>
110 }
111 <button (click)="addMutation.mutate('Item')">Add</button>
112 `,
113})
114export class Todos {
115 readonly #queryClient = inject(QueryClient)
116β
117 readonly addMutation = injectMutation(() => ({
118 mutationFn: addTodo,
119 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
120 }))
121}
122```
123β
124Optimistic update via `onMutate`, rolling back on `onError`:
125```angular-ts
126@Component({
127 selector: 'todos',
128 template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
129})
130export class Todos {
131 readonly #queryClient = inject(QueryClient)
132β
133 readonly addMutation = injectMutation(() => ({
134 mutationFn: addTodo,
135 onMutate: async (newTodo) => {
136 await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
137 const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
138β
139 this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
140 ...(old ?? []),
141 newTodo,
142 ])
143β
144 // Passed to `onError` as `onMutateResult` if the mutation fails.
145 return { previousTodos }
146 },
147 onError: (_err, _newTodo, onMutateResult) => {
148 this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
149 },
150 onSettled: () => {
151 this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
152 },
153 }))
154}
155```
156β
157Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a promise per
158call instead, so you can wait for all of them when they succeed:
159```angular-ts
160@Component({
161 selector: 'todos',
162 template: `
163 <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
164 `,
165})
166export class Todos {
167 readonly #queryClient = inject(QueryClient)
168β
169 readonly addMutation = injectMutation(() => ({
170 mutationFn: addTodo,
171 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
172 }))
173β
174 async handleAddAll(todos: Array<string>) {
175 try {
176 await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
177 } catch (error) {
178 console.error('Failed to add todos:', error)
179 }
180 }
181}
182```
183β
184If some of the mutations above can fail independently of the others, and you want to know which ones did β
185rather than losing that information the moment the first one rejects β swap `Promise.all` for
186`Promise.allSettled`:
187```angular-ts
188@Component({
189 selector: 'todos',
190 template: `
191 <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
192 `,
193})
194export class Todos {
195 readonly #queryClient = inject(QueryClient)
196β
197 readonly addMutation = injectMutation(() => ({
198 mutationFn: addTodo,
199 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
200 }))
201β
202 async handleAddAll(todos: Array<string>) {
203 const addResults = await Promise.allSettled(
204 todos.map((todo) => this.addMutation.mutateAsync(todo)),
205 )
206β
207 addResults.forEach((addResult, index) => {
208 if (addResult.status === 'rejected') {
209 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
210 }
211 })
212 }
213}
214```