1

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);
    },
  });

1 Answer 1

3

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.

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

Comments

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.