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

264
Views
Rollback to previous state is not working in react query (optimistic updates)

I am using optimistic update react query, here i am increasing the followers and plus updating the following state right below is my code:

Everything is working as it should but when the error comes then previousSnapshot and previousUserData is not holding the previous value it is again and again returning the mutated or the updated data in the error block, it is supposed to return the previous state but it is not, please let me know what i am doing wrong here.

const callFavoriteUserMutation = useMutation(favoriteUser, {
    onMutate: async _id => {
      const previousSnapshot = queryClient.getQueryData(`${id}userdetail`);
      const previousUserData = queryClient.getQueryData('getUserInfo');

      queryClient.setQueryData(`${id}userdetail`, (oldData: any) => {
        const updatedData = {...oldData};
        updatedData.stats.followers += 1;
        updatedData.following = true;
        return updatedData;
      });

      queryClient.setQueryData('getUserInfo', (oldUserData: any) => {
        const updatedData = {...oldUserData};
        updatedData.stats.following += 1;
        return updatedData;       
      });

      return {previousSnapshot, previousUserData};
    },

    onError: (error_code, _id, context: any) => {
      queryClient.setQueryData(`${id}userdetail`, context.previousSnapshot);
      queryClient.setQueryData('getUserInfo', context.previousUserData);
      setFollowing(context.previousSnapshot.following);
      setNoOfFollowers(context.previousSnapshot.stats?.followers);
      setNoOfFollowing(context.previousSnapshot?.stats?.following);
    },
  });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

it's because you are mutating the original data. You only create a shallow copy:

const updatedData = {...oldData};

but then mutate deep properties:

updatedData.stats.followers += 1;
updatedData.following = true;

please update immutably, or create a deep copy, or use something like immer if you prefer the mutable syntax.

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!