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

104
Vistas
Two React useEffect functions affecting the same state

I have a certain piece of state that is updated via api calls. I have multiple components that affect this state and am running into an issue. Basically, the issue comes down to how the state is set because of the time it takes for the api call to finish.

Basically: Component 1 is loaded and the useEffect is triggered to update the state Component 2 is loaded right afterwards and also has a useEffect making the same api call for different data

If the api call in Component 1 takes longer than Component 2, Component 2's set state is then overwritten by the set state of Component 1 once its api call finishes, even if Component 1 is no longer mounted.

Is there a way in functional components to cancel any api calls/setting of state when the component is unmounted? Thanks.

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

0

I found the basic answer here in this other question: Canceling an Axios REST call in React Hooks useEffects cleanup failing

Basically, I needed to have the useEffect function return something in order for it to be cleaned up. It is easier to explain in code, so I will put that below:

  useEffect(() => {
    let unMounted = false;
    const onLoad = async () => {
      const data= await axios.get();
      !unMounted &&
        setData(data);
    };

    onLoad();

    return () => {
      unMounted = true;
    };
  }, []);
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