0

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 }
      }
4
  • Try this const previousCurrentPost = {...queryClient.getQueryData(['currentPost'])} Commented Feb 15, 2022 at 15:38
  • @VitaliyRayets thx for the help, but doesnt work :( Commented Feb 15, 2022 at 18:46
  • Try with deep clone const previousCurrentPost = JSON.parse(JSON.stringify(queryClient.getQueryData(['currentPost']))) Commented Feb 16, 2022 at 8:07
  • @VitaliyRayets damn, you are right! Thank you! Commented Feb 16, 2022 at 18:50

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

true, thanks for help
please use immer if you want to mutate data structures. In everything React, it is better to work immutably.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.