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

useMutation.md

248 lines11.7 KB

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