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

injectMutation.md

200 lines10.8 KB

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>(optionsFn: () => CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>): CreateMutationResult<TData, TError, TVariables, TOnMutateResult>;
10```
11​
12Defined in: [packages/angular-query/src/inject-mutation.ts:154](https://github.com/TanStack/query/blob/main/packages/angular-query/src/inject-mutation.ts#L154)
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### optionsFn
38​
39() => [`CreateMutationOptions`](../interfaces/CreateMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
40​
41A function that returns mutation options. Similar to `computed` from Angular, this
42function runs in the reactive context, so signals read inside it drive the mutation's options.
43​
44<a id="optionsFn-properties"></a>
45​
46#### `optionsFn` properties
47​
48| Property | Type | Default value | Description |
49| ------ | ------ | ------ | ------ |
50| <a id="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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="optionsFn-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​
63## Returns
64​
65[`CreateMutationResult`](../type-aliases/CreateMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
66​
67The mutation result. Value fields are exposed as a `Signal` β€” read `data`/`error` by calling them
68(e.g. `mutation.data()`) β€” while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
69unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
70`data` is defined.
71​
72## Remarks
73​
74`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
75second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
76the shared mutation definition. Callbacks defined in `optionsFn` fire for every mutation; per-call
77callbacks fire only for the latest call you've made β€” `mutateAsync` gives you a promise per call instead,
78so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
79​
80## See
81​
82 - https://tanstack.com/query/latest/docs/framework/angular/guides/mutations
83 - [mutationOptions](mutationOptions.md) to share these options across multiple `injectMutation` call sites, or to look
84the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
85​
86## Examples
87​
88```angular-ts
89@Component({
90 selector: 'todos',
91 template: `
92 @if (addMutation.isPending()) {
93 <span>Adding todo...</span>
94 } @else if (addMutation.isError()) {
95 <div>An error occurred: {{ addMutation.error()?.message }}</div>
96 }
97 <button (click)="addMutation.mutate('Item')">Add</button>
98 `,
99})
100export class Todos {
101 readonly #queryClient = inject(QueryClient)
102​
103 readonly addMutation = injectMutation(() => ({
104 mutationFn: addTodo,
105 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
106 }))
108```
109​
110Optimistic update via `onMutate`, rolling back on `onError`:
111```angular-ts
112@Component({
113 selector: 'todos',
114 template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
115})
116export class Todos {
117 readonly #queryClient = inject(QueryClient)
118​
119 readonly addMutation = injectMutation(() => ({
120 mutationFn: addTodo,
121 onMutate: async (newTodo) => {
122 await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
123 const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
124​
125 this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
126 ...(old ?? []),
127 newTodo,
128 ])
129​
130 // Passed to `onError` as `onMutateResult` if the mutation fails.
131 return { previousTodos }
132 },
133 onError: (_err, _newTodo, onMutateResult) => {
134 this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
135 },
136 onSettled: () => {
137 this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
138 },
139 }))
141```
142​
143Callbacks passed per call to `mutate` only fire for the last call β€” `mutateAsync` gives you a promise per
144call instead, so you can wait for all of them when they succeed:
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})
152export 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 try {
162 await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
163 } catch (error) {
164 console.error('Failed to add todos:', error)
165 }
166 }
168```
169​
170If some of the mutations above can fail independently of the others, and you want to know which ones did β€”
171rather than losing that information the moment the first one rejects β€” swap `Promise.all` for
172`Promise.allSettled`:
173```angular-ts
174@Component({
175 selector: 'todos',
176 template: `
177 <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
178 `,
179})
180export class Todos {
181 readonly #queryClient = inject(QueryClient)
182​
183 readonly addMutation = injectMutation(() => ({
184 mutationFn: addTodo,
185 onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
186 }))
187​
188 async handleAddAll(todos: Array<string>) {
189 const addResults = await Promise.allSettled(
190 todos.map((todo) => this.addMutation.mutateAsync(todo)),
191 )
192​
193 addResults.forEach((addResult, index) => {
194 if (addResult.status === 'rejected') {
195 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
196 }
197 })
198 }
200```