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

updates-from-mutation-responses.md

77 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#queryclientsetquerydata) method:
7​
8[//]: # 'Example'
9```tsx
10const queryClient = useQueryClient()
11​
12const mutation = useMutation({
13 mutationFn: editTodo,
14 onSuccess: data => {
15 queryClient.setQueryData(['todo', { id: 5 }], data)
16 }
17})
18​
19mutation.mutate({
20 id: 5,
21 name: 'Do the laundry',
22})
23​
24// The query below will be updated with the response from the
25// successful mutation
26const { status, data, error } = useQuery({
27 queryKey: ['todo', { id: 5 }],
28 queryFn: fetchTodoById,
29})
30```
31[//]: # 'Example'
32​
33You might want to tie the `onSuccess` logic into a reusable mutation, for that you can
34create a custom hook like this:
35​
36[//]: # 'Example2'
37```tsx
38const useMutateTodo = () => {
39 const queryClient = useQueryClient()
40​
41 return useMutation({
42 mutationFn: editTodo,
43 // Notice the second argument is the variables object that the `mutate` function receives
44 onSuccess: (data, variables) => {
45 queryClient.setQueryData(['todo', { id: variables.id }], data)
46 },
47 })
49```
50[//]: # 'Example2'
51​
52## Immutability
53​
54Updates via `setQueryData` must be performed in an _immutable_ way. **DO NOT** attempt to write directly to the cache by mutating data (that you retrieved via from the cache) in place. It might work at first but can lead to subtle bugs along the way.
55​
56[//]: # 'Example3'
57```tsx
58queryClient.setQueryData(
59 ['posts', { id }],
60 (oldData) => {
61 if (oldData) {
62 // ❌ do not try this
63 oldData.title = 'my new post title'
64 }
65 return oldData
66 })
67​
68queryClient.setQueryData(
69 ['posts', { id }],
70 // βœ… this is the way
71 (oldData) => oldData ? {
72 ...oldData,
73 title: 'my new post title'
74 } : oldData
76```
77[//]: # 'Example3'