everyone! I'm new to react-query and I was trying to make an optimistic update, using mutation function, but faced a problem, that I can not fetch a previous value from the query. What am I doing wrong?
previousCurrentPost - always return a value, that already been updated
My onMutate func:
{
onMutate: async (postOrComment: any, emojiType?: string) => {
await queryClient.cancelQueries(['currentPost'])
// Snapshot the previous value
const previousCurrentPost = queryClient.getQueryData(['currentPost'])
// Optimistically update to the new value
queryClient.setQueryData(['currentPost'], (oldPost: any) => {
const updated = { ...oldPost }
updated.state.is_liked = !oldPost.state.is_liked
updated.stat.like_count = postOrComment.state.is_liked
? oldPost.stat.like_count + 1
: oldPost.stat.like_count - 1
if (emojiType) {
updated.state.like_emoji = emojiType
}
return updated
})
return { previousCurrentPost }
}
const previousCurrentPost = {...queryClient.getQueryData(['currentPost'])}const previousCurrentPost = JSON.parse(JSON.stringify(queryClient.getQueryData(['currentPost'])))