Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

269
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda