cjmling / findings

Notes on stuff i finds worth keeping for quick reference later on.
2 stars 0 forks source link

React useEffect fix race condition #324

Open cjmling opened 2 years ago

cjmling commented 2 years ago

https://maxrozen.com/race-conditions-fetching-data-react-with-useeffect

useEffect(() => {
  let active = true;
  const fetchData = async () => {
    setTimeout(async () => {
      const response = await fetch(`https://swapi.dev/api/people/${props.id}/`);
      const newData = await response.json();
      if (active) {
        setFetchedId(props.id);
        setData(newData);
      }
    }, Math.round(Math.random() * 12000));
  };
  fetchData();
  return () => {
    active = false;
  };
}, [props.id]);

react useEffect race condition useeffect