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

updates-from-mutation-responses.md

84 lines2.2 KB

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 })
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,
82```
83​
84[//]: # 'Example3'