Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

78
Views
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 }
      }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!