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