Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda