-1

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.

  • 2
    Code is worth 1024 words. – T.J. Crowder Mar 23 '22 at 12:22
  • 3
    *"Is there a way in functional components to cancel any api calls/setting of state when the component is unmounted?"* The [cleanup callback of a `useEffect` with a `[]` dependencies array](https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect) is called only when the component is unmounted. It's not clear to me that that's what you should do, but if that's what you want to do, that's where you'd do it. – T.J. Crowder Mar 23 '22 at 12:23

1 Answers1

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;
    };
  }, []);