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

useMutation.md

217 lines5.9 KB

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