Vladimir Kosenko
Vladimir Kosenko

Reputation: 3

React-query optimistic update on mutation

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 }
      }

Upvotes: 0

Views: 2158

Answers (1)

anonkey
anonkey

Reputation: 102

It's because { ...oldPost } only do a shallow copy not a deep copy .

So oldPost.state and updated.state are the same object and when you do your assignment it's updating in oldPost and in updated

Upvotes: 1

Related Questions