Open History to see the last commit
1---
2id: updates-from-mutation-responses
3title: Updates from Mutation Responses
4---
5β
6When dealing with mutations that **update** objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of refetching any queries for that item and wasting a network call for data we already have, we can take advantage of the object returned by the mutation function and update the existing query with the new data immediately using the [Query Client's `setQueryData`](../../../../reference/QueryClient.md#queryclientsetquerydata) method:
7β
8[//]: # 'Example'
9β
10```tsx
11const queryClient = useQueryClient()
12β
13const mutation = useMutation({
14 mutationFn: editTodo,
15 onSuccess: (data) => {
16 queryClient.setQueryData(['todo', { id: 5 }], data)
17 },
18})
19β
20mutation.mutate({
21 id: 5,
22 name: 'Do the laundry',
23})
24β
25// The query below will be updated with the response from the
26// successful mutation
27const { status, data, error } = useQuery({
28 queryKey: ['todo', { id: 5 }],
29 queryFn: fetchTodoById,
30})
31```
32β
33[//]: # 'Example'
34β
35You might want to tie the `onSuccess` logic into a reusable mutation, for that you can
36create a custom hook like this:
37β
38[//]: # 'Example2'
39β
40```tsx
41const useMutateTodo = () => {
42 const queryClient = useQueryClient()
43β
44 return useMutation({
45 mutationFn: editTodo,
46 // Notice the second argument is the variables object that the `mutate` function receives
47 onSuccess: (data, variables) => {
48 queryClient.setQueryData(['todo', { id: variables.id }], data)
49 },
50 })
51}
52```
53β
54[//]: # 'Example2'
55β
56## Immutability
57β
58Updates via `setQueryData` must be performed in an _immutable_ way. **DO NOT** attempt to write directly to the cache by mutating data (that you retrieved from the cache) in place. It might work at first but can lead to subtle bugs along the way.
59β
60[//]: # 'Example3'
61β
62```tsx
63queryClient.setQueryData(['posts', { id }], (oldData) => {
64 if (oldData) {
65 // β do not try this
66 oldData.title = 'my new post title'
67 }
68 return oldData
69})
70β
71queryClient.setQueryData(
72 ['posts', { id }],
73 // β
this is the way
74 (oldData) =>
75 oldData
76 ? {
77 ...oldData,
78 title: 'my new post title',
79 }
80 : oldData,
81)
82```
83β
84[//]: # 'Example3'