Skip to content

Commit 5c688c0

Browse files
committed
handle mutation response
1 parent 969b987 commit 5c688c0

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,10 @@ On react-query heroes page we have displayed different heroes. If we click on th
104104

105105
If we add flag `keepPreviousData` into the useQuery options, when we paginate to next page, the data from the previous page is still displayed till the new data is successfully fetched.
106106

107+
**13. react-query - Handling mutation response**
108+
109+
Handling mutation response will save you additional network request.
110+
107111
## Available Scripts
108112

109113
In the project directory, you can run:

db.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@
3939
"name": "Add automatic",
4040
"alterEgo": "Okej it works",
4141
"id": 8
42+
},
43+
{
44+
"name": "Test",
45+
"alterEgo": "Test",
46+
"id": 9
4247
}
4348
],
4449
"friends": [

src/lib/hooks/useSuperHeroesData.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,13 @@ export const useSuperHeroesData = ({ onSuccess, onError }: Props) => {
2525
export const useAddSuperHeroData = () => {
2626
const queryClient = useQueryClient()
2727
return useMutation(addSuperHero, {
28-
onSuccess: () => {
29-
queryClient.invalidateQueries('super-heroes')
28+
onSuccess: (response) => {
29+
queryClient.setQueryData('super-heroes', (oldQueryData: any) => {
30+
return {
31+
...oldQueryData,
32+
data: [...oldQueryData.data, response.data],
33+
}
34+
})
3035
},
3136
})
3237
}

0 commit comments

Comments
 (0)