Open History to see the last commit
1---
2id: mutations
3title: Mutations
4---
5β
6Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a `useMutation` hook.
7β
8Here's an example of a mutation that adds a new todo to the server:
9β
10[//]: # 'Example'
11β
12```tsx
13function App() {
14 const mutation = useMutation({
15 mutationFn: (newTodo) => {
16 return axios.post('/todos', newTodo)
17 },
18 })
19β
20 return (
21 <div>
22 {mutation.isLoading ? (
23 'Adding todo...'
24 ) : (
25 <>
26 {mutation.isError ? (
27 <div>An error occurred: {mutation.error.message}</div>
28 ) : null}
29β
30 {mutation.isSuccess ? <div>Todo added!</div> : null}
31β
32 <button
33 onClick={() => {
34 mutation.mutate({ id: new Date(), title: 'Do Laundry' })
35 }}
36 >
37 Create Todo
38 </button>
39 </>
40 )}
41 </div>
42 )
43}
44```
45β
46[//]: # 'Example'
47β
48A mutation can only be in one of the following states at any given moment:
49β
50- `isIdle` or `status === 'idle'` - The mutation is currently idle or in a fresh/reset state
51- `isLoading` or `status === 'loading'` - The mutation is currently running
52- `isError` or `status === 'error'` - The mutation encountered an error
53- `isSuccess` or `status === 'success'` - The mutation was successful and mutation data is available
54β
55Beyond those primary states, more information is available depending on the state of the mutation:
56β
57- `error` - If the mutation is in an `error` state, the error is available via the `error` property.
58- `data` - If the mutation is in a `success` state, the data is available via the `data` property.
59β
60In the example above, you also saw that you can pass variables to your mutations function by calling the `mutate` function with a **single variable or object**.
61β
62Even with just variables, mutations aren't all that special, but when used with the `onSuccess` option, the [Query Client's `invalidateQueries` method](../reference/QueryClient#queryclientinvalidatequeries) and the [Query Client's `setQueryData` method](../reference/QueryClient#queryclientsetquerydata), mutations become a very powerful tool.
63β
64[//]: # 'Info1'
65β
66> IMPORTANT: The `mutate` function is an asynchronous function, which means you cannot use it directly in an event callback in **React 16 and earlier**. If you need to access the event in `onSubmit` you need to wrap `mutate` in another function. This is due to [React event pooling](https://reactjs.org/docs/legacy-event-pooling.html).
67β
68[//]: # 'Info1'
69[//]: # 'Example2'
70β
71```tsx
72// This will not work in React 16 and earlier
73const CreateTodo = () => {
74 const mutation = useMutation({
75 mutationFn: (event) => {
76 event.preventDefault()
77 return fetch('/api', new FormData(event.target))
78 },
79 })
80β
81 return <form onSubmit={mutation.mutate}>...</form>
82}
83β
84// This will work
85const CreateTodo = () => {
86 const mutation = useMutation({
87 mutationFn: (formData) => {
88 return fetch('/api', formData)
89 },
90 })
91 const onSubmit = (event) => {
92 event.preventDefault()
93 mutation.mutate(new FormData(event.target))
94 }
95β
96 return <form onSubmit={onSubmit}>...</form>
97}
98```
99β
100[//]: # 'Example2'
101β
102## Resetting Mutation State
103β
104It's sometimes the case that you need to clear the `error` or `data` of a mutation request. To do this, you can use the `reset` function to handle this:
105β
106[//]: # 'Example3'
107β
108```tsx
109const CreateTodo = () => {
110 const [title, setTitle] = useState('')
111 const mutation = useMutation({ mutationFn: createTodo })
112β
113 const onCreateTodo = (e) => {
114 e.preventDefault()
115 mutation.mutate({ title })
116 }
117β
118 return (
119 <form onSubmit={onCreateTodo}>
120 {mutation.error && (
121 <h5 onClick={() => mutation.reset()}>{mutation.error}</h5>
122 )}
123 <input
124 type="text"
125 value={title}
126 onChange={(e) => setTitle(e.target.value)}
127 />
128 <br />
129 <button type="submit">Create Todo</button>
130 </form>
131 )
132}
133```
134β
135[//]: # 'Example3'
136β
137## Mutation Side Effects
138β
139`useMutation` comes with some helper options that allow quick and easy side-effects at any stage during the mutation lifecycle. These come in handy for both [invalidating and refetching queries after mutations](../guides/invalidations-from-mutations) and even [optimistic updates](../guides/optimistic-updates)
140β
141[//]: # 'Example4'
142β
143```tsx
144useMutation({
145 mutationFn: addTodo,
146 onMutate: (variables) => {
147 // A mutation is about to happen!
148β
149 // Optionally return a context containing data to use when for example rolling back
150 return { id: 1 }
151 },
152 onError: (error, variables, context) => {
153 // An error happened!
154 console.log(`rolling back optimistic update with id ${context.id}`)
155 },
156 onSuccess: (data, variables, context) => {
157 // Boom baby!
158 },
159 onSettled: (data, error, variables, context) => {
160 // Error or success... doesn't matter!
161 },
162})
163```
164β
165[//]: # 'Example4'
166β
167When returning a promise in any of the callback functions it will first be awaited before the next callback is called:
168β
169[//]: # 'Example5'
170β
171```tsx
172useMutation({
173 mutationFn: addTodo,
174 onSuccess: async () => {
175 console.log("I'm first!")
176 },
177 onSettled: async () => {
178 console.log("I'm second!")
179 },
180})
181```
182β
183[//]: # 'Example5'
184β
185You might find that you want to **trigger additional callbacks** beyond the ones defined on `useMutation` when calling `mutate`. This can be used to trigger component-specific side effects. To do that, you can provide any of the same callback options to the `mutate` function after your mutation variable. Supported options include: `onSuccess`, `onError` and `onSettled`. Please keep in mind that those additional callbacks won't run if your component unmounts _before_ the mutation finishes.
186β
187[//]: # 'Example6'
188β
189```tsx
190useMutation({
191 mutationFn: addTodo,
192 onSuccess: (data, variables, context) => {
193 // I will fire first
194 },
195 onError: (error, variables, context) => {
196 // I will fire first
197 },
198 onSettled: (data, error, variables, context) => {
199 // I will fire first
200 },
201})
202β
203mutate(todo, {
204 onSuccess: (data, variables, context) => {
205 // I will fire second!
206 },
207 onError: (error, variables, context) => {
208 // I will fire second!
209 },
210 onSettled: (data, error, variables, context) => {
211 // I will fire second!
212 },
213})
214```
215β
216[//]: # 'Example6'
217β
218### Consecutive mutations
219β
220There is a slight difference in handling `onSuccess`, `onError` and `onSettled` callbacks when it comes to consecutive mutations. When passed to the `mutate` function, they will be fired up only _once_ and only if the component is still mounted. This is due to the fact that mutation observer is removed and resubscribed every time when the `mutate` function is called. On the contrary, `useMutation` handlers execute for each `mutate` call.
221β
222> Be aware that most likely, `mutationFn` passed to `useMutation` is asynchronous. In that case, the order in which mutations are fulfilled may differ from the order of `mutate` function calls.
223β
224[//]: # 'Example7'
225β
226```tsx
227useMutation({
228 mutationFn: addTodo,
229 onSuccess: (data, error, variables, context) => {
230 // Will be called 3 times
231 },
232})
233β
234[('Todo 1', 'Todo 2', 'Todo 3')].forEach((todo) => {
235 mutate(todo, {
236 onSuccess: (data, error, variables, context) => {
237 // Will execute only once, for the last mutation (Todo 3),
238 // regardless which mutation resolves first
239 },
240 })
241})
242```
243β
244[//]: # 'Example7'
245β
246## Promises
247β
248Use `mutateAsync` instead of `mutate` to get a promise which will resolve on success or throw on an error. This can for example be used to compose side effects.
249β
250[//]: # 'Example8'
251β
252```tsx
253const mutation = useMutation({ mutationFn: addTodo })
254β
255try {
256 const todo = await mutation.mutateAsync(todo)
257 console.log(todo)
258} catch (error) {
259 console.error(error)
260} finally {
261 console.log('done')
262}
263```
264β
265[//]: # 'Example8'
266β
267## Retry
268β
269By default TanStack Query will not retry a mutation on error, but it is possible with the `retry` option:
270β
271[//]: # 'Example9'
272β
273```tsx
274const mutation = useMutation({
275 mutationFn: addTodo,
276 retry: 3,
277})
278```
279β
280[//]: # 'Example9'
281β
282If mutations fail because the device is offline, they will be retried in the same order when the device reconnects.
283β
284## Persist mutations
285β
286Mutations can be persisted to storage if needed and resumed at a later point. This can be done with the hydration functions:
287β
288[//]: # 'Example10'
289β
290```tsx
291const queryClient = new QueryClient()
292β
293// Define the "addTodo" mutation
294queryClient.setMutationDefaults(['addTodo'], {
295 mutationFn: addTodo,
296 onMutate: async (variables) => {
297 // Cancel current queries for the todos list
298 await queryClient.cancelQueries({ queryKey: ['todos'] })
299β
300 // Create optimistic todo
301 const optimisticTodo = { id: uuid(), title: variables.title }
302β
303 // Add optimistic todo to todos list
304 queryClient.setQueryData(['todos'], (old) => [...old, optimisticTodo])
305β
306 // Return context with the optimistic todo
307 return { optimisticTodo }
308 },
309 onSuccess: (result, variables, context) => {
310 // Replace optimistic todo in the todos list with the result
311 queryClient.setQueryData(['todos'], (old) =>
312 old.map((todo) =>
313 todo.id === context.optimisticTodo.id ? result : todo,
314 ),
315 )
316 },
317 onError: (error, variables, context) => {
318 // Remove optimistic todo from the todos list
319 queryClient.setQueryData(['todos'], (old) =>
320 old.filter((todo) => todo.id !== context.optimisticTodo.id),
321 )
322 },
323 retry: 3,
324})
325β
326// Start mutation in some component:
327const mutation = useMutation({ mutationKey: ['addTodo'] })
328mutation.mutate({ title: 'title' })
329β
330// If the mutation has been paused because the device is for example offline,
331// Then the paused mutation can be dehydrated when the application quits:
332const state = dehydrate(queryClient)
333β
334// The mutation can then be hydrated again when the application is started:
335hydrate(queryClient, state)
336β
337// Resume the paused mutations:
338queryClient.resumePausedMutations()
339```
340β
341[//]: # 'Example10'
342β
343### Persisting Offline mutations
344β
345If you persist offline mutations with the [persistQueryClient plugin](../plugins/persistQueryClient), mutations cannot be resumed when the page is reloaded unless you provide a default mutation function.
346β
347This is a technical limitation. When persisting to an external storage, only the state of mutations is persisted, as functions cannot be serialized. After hydration, the component that triggers the mutation might not be mounted, so calling `resumePausedMutations` might yield an error: `No mutationFn found`.
348β
349[//]: # 'Example11'
350β
351```tsx
352const persister = createSyncStoragePersister({
353 storage: window.localStorage,
354})
355const queryClient = new QueryClient({
356 defaultOptions: {
357 queries: {
358 cacheTime: 1000 * 60 * 60 * 24, // 24 hours
359 },
360 },
361})
362β
363// we need a default mutation function so that paused mutations can resume after a page reload
364queryClient.setMutationDefaults(['todos'], {
365 mutationFn: ({ id, data }) => {
366 return api.updateTodo(id, data)
367 },
368})
369β
370export default function App() {
371 return (
372 <PersistQueryClientProvider
373 client={queryClient}
374 persistOptions={{ persister }}
375 onSuccess={() => {
376 // resume mutations after initial restore from localStorage was successful
377 queryClient.resumePausedMutations()
378 }}
379 >
380 <RestOfTheApp />
381 </PersistQueryClientProvider>
382 )
383}
384```
385β
386[//]: # 'Example11'
387β
388We also have an extensive [offline example](../examples/react/offline) that covers both queries and mutations.
389β
390[//]: # 'Materials'
391β
392## Further reading
393β
394For more information about mutations, have a look at [#12: Mastering Mutations in React Query](../community/tkdodos-blog#12-mastering-mutations-in-react-query) from
395the Community Resources.
396β
397[//]: # 'Materials'