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

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

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 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