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

105
Vistas
React function uses outdated state

I am using react-query to fetch external data, based on the current state here is how the code looks like

const Home = () => {
  const queryClient = useQueryClient();
  const [group, setGroup] = useState(1);

  const query = useQuery('/query', async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });

  useEffect(() => {
    queryClient.invalidateQueries('/query');
  }, [group, queryClient]);

  return (
    <div>
      <button onClick={() => setGroup(1)}>First group</button>
      <button onClick={() => setGroup(2)}>Second group</button>
    </div>
  );
};

There are 2 buttons that changes the state (group), and when the state changes (useEffect) I invalidate old queries to send new queries but the problem is that the callback has only the initial state and not the updated state and when it get executed it prints out the initial state

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think that you should modify your useQuery section in this way

const query = useQuery(['/query', group], async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });
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