Open History to see the last commit
1---
2id: useMutation
3title: useMutation
4---
5β
6```ts
7function useMutation<TData, TError, TVariables, TOnMutateResult>(options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, queryClient?: QueryClient): UseMutationResult<TData, TError, TVariables, TOnMutateResult>;
8```
9β
10Defined in: [packages/preact-query/src/useMutation.ts:188](https://github.com/TanStack/query/blob/main/packages/preact-query/src/useMutation.ts#L188)
11β
12Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
13`useMutation` is the hook for that.
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### options
36β
37[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
38β
39The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use β everything you can pass to `useMutation`.
40β
41<a id="options-properties"></a>
42β
43#### `options` properties
44β
45| Property | Type | Default value | Description |
46| ------ | ------ | ------ | ------ |
47| <a id="options-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. |
48| <a id="options-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`. |
49| <a id="options-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. |
50| <a id="options-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`. |
51| <a id="options-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. |
52| <a id="options-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. |
53| <a id="options-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. |
54| <a id="options-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. |
55| <a id="options-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. |
56| <a id="options-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. |
57| <a id="options-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. |
58| <a id="options-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. |
59| <a id="options-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`). |
60β
61### queryClient?
62β
63[`QueryClient`](../classes/QueryClient.md)
64β
65Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
66be used.
67β
68## Returns
69β
70[`UseMutationResult`](../type-aliases/UseMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
71β
72`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
73argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
74mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
75fire only for the latest call you've made, and only while the component is still mounted β unmounting before
76the mutation settles removes the subscription and prevents them from firing.
77β
78<a id="result-properties"></a>
79β
80### Result properties
81β
82Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes.
83β
84## Throws
85β
86The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is
87thrown to the nearest error boundary.
88β
89## See
90β
91[mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look
92the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
93β
94## Examples
95β
96```tsx
97import { useMutation, useQueryClient } from '@tanstack/preact-query'
98β
99function AddTodo() {
100 const queryClient = useQueryClient()
101β
102 const addMutation = useMutation({
103 mutationFn: addTodo,
104 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
105 })
106β
107 return (
108 <button
109 onClick={() =>
110 addMutation.mutate('Item', {
111 onError: (error) => console.error('Failed to add item:', error),
112 })
113 }
114 >
115 Add
116 </button>
117 )
118}
119```
120β
121Rendering the mutation's own state, rather than just firing it off:
122```tsx
123import { useMutation, useQueryClient } from '@tanstack/preact-query'
124β
125function AddTodo() {
126 const queryClient = useQueryClient()
127β
128 const addMutation = useMutation({
129 mutationFn: addTodo,
130 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
131 })
132β
133 return (
134 <div>
135 {addMutation.isPending ? (
136 'Adding todo...'
137 ) : (
138 <>
139 {addMutation.isError ? (
140 <div>An error occurred: {addMutation.error.message}</div>
141 ) : null}
142 <button onClick={() => addMutation.mutate('Item')}>Add</button>
143 </>
144 )}
145 </div>
146 )
147}
148```
149β
150Optimistic update via `onMutate`, rolling back on `onError`:
151```tsx
152import { useMutation, useQueryClient } from '@tanstack/preact-query'
153β
154function AddTodo() {
155 const queryClient = useQueryClient()
156β
157 const addMutation = useMutation({
158 mutationFn: addTodo,
159 onMutate: async (newTodo) => {
160 await queryClient.cancelQueries({ queryKey: ['todos'] })
161 const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
162β
163 queryClient.setQueryData<Array<string>>(['todos'], (old) => [
164 ...(old ?? []),
165 newTodo,
166 ])
167β
168 // Passed to `onError` as `onMutateResult` if the mutation fails.
169 return { previousTodos }
170 },
171 onError: (_err, _newTodo, onMutateResult) => {
172 queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
173 },
174 onSettled: () => {
175 queryClient.invalidateQueries({ queryKey: ['todos'] })
176 },
177 })
178β
179 return (
180 <button onClick={() => addMutation.mutate('Item')}>Add</button>
181 )
182}
183```
184β
185Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
186promise per call instead, so you can wait for all of them when they succeed:
187```tsx
188import { useMutation, useQueryClient } from '@tanstack/preact-query'
189β
190function AddTodos() {
191 const queryClient = useQueryClient()
192β
193 const addMutation = useMutation({
194 mutationFn: addTodo,
195 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
196 })
197β
198 async function handleAddAll(todos: Array<string>) {
199 try {
200 await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
201 } catch (error) {
202 console.error('Failed to add todos:', error)
203 }
204 }
205β
206 return (
207 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
208 Add all
209 </button>
210 )
211}
212```
213β
214If some of the mutations above can fail independently of the others, and you want to know which ones
215did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
216`Promise.allSettled`:
217```tsx
218import { useMutation, useQueryClient } from '@tanstack/preact-query'
219β
220function AddTodos() {
221 const queryClient = useQueryClient()
222β
223 const addMutation = useMutation({
224 mutationFn: addTodo,
225 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
226 })
227β
228 async function handleAddAll(todos: Array<string>) {
229 const addResults = await Promise.allSettled(
230 todos.map((todo) => addMutation.mutateAsync(todo)),
231 )
232β
233 addResults.forEach((addResult, index) => {
234 if (addResult.status === 'rejected') {
235 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
236 }
237 })
238 }
239β
240 return (
241 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
242 Add all
243 </button>
244 )
245}
246```