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

mutations.md

397 lines11.5 KB

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 )
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>
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>
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 )
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')
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 )
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'