Reputation: 107
RTKQ I'm creating a mutation. I'm trying to update it with the optimistic update method, but in the examples I've found, the scenario is always like this. postEdit mutation works. getPost request is made in onQueryStarted and it is finalized. In my scenario, instead of sending a getPost request, postEdit returns the current post value as a response if the statusCode is positive. In this case, I couldn't find how to update the store, do you have any ideas?
Upvotes: 4
Views: 4074
Reputation: 3860
That's not the right way to use RTK Query or any other fetch library that handles revalidation for you like useSWR. You want to retrieve data from a query and perform revalidation after mutations on that data so the query gets automatically re-executed after each mutation and your UI is updated.
Let me give you this example I used in one of my applications:
addPost: builder.mutation({
query: (body) => {
console.log('ADDING POST', body)
return {
url: `add-post`,
method: 'POST',
body,
}
},
invalidatesTags: ['Posts'],
onQueryStarted(body, { dispatch, queryFulfilled }) {
const patchResult = dispatch(
socialApi.util.updateQueryData(
'getPosts',
{ _id: body.profileOwner_id, limit: body.limit },
(draft) => {
console.log('POSTS ARRAY DRAFT', draft)
draft.unshift({
...body,
shareable: true,
title: 'published a new post.',
timestamp: new Date(),
likes: [],
})
}
)
)
queryFulfilled.catch(patchResult.undo)
},
}),
In this case I invalidate 'Posts' which triggers the query to User's Posts after the user adds a new Post. No need to add the new post manually in response to the mutation.
And as you can see, this way I can use the optimistic update util method .updateQueryData()
, "draft" is the Posts list, I just add a new Post object to that array and that is automatically rendered as soon as the mutation is triggered.
Upvotes: 6