skip to Main Content

I am trying to fetch some data inside my component using useEffect hook and it is going in infinite loop. I am using this react tutorial page and this race conditions page for reference. Here is my code.

function AppNew () {
  const [matchData, setMatchData] = useState(null)
  const [matchesLoaded, setMatchesLoaded] = useState(false)

  useEffect(() => {
    let active = true;
    
    const responseMatches = axiosInstance.get("api/matches/")
        .then(responseMatches => {
            if (active) {
                setMatchData(responseMatches.data);
                setMatchesLoaded(true);
            }
        })
        .catch (error => {
            throw error;
        })

    return () => {
        active = false
    }
  });
  
  console.log("match data: ");
  console.log(matchData);

} 

The API returns valid data in about 10ms. console.log statements for matchData keep writing the data to the console infinitely.

2

Answers


  1. useEffect(() => {    
    const responseMatches = axiosInstance.get("api/matches/")
        .then(responseMatches => {
            if (active) {
                setMatchData(responseMatches.data);
                setMatchesLoaded(true);
            }
        })
        .catch (error => {
            throw error;
        })
    },[]);
    

    dependency array is missing as a second parameter of useEffect

    Login or Signup to reply.
  2. You are calling the "api/matches" API, and as a result, both setMatchData and setMatchesLoaded are being triggered.
    However, since you didn’t set a dependency array, useEffect will run on every render.
    Because of this, your useEffect is being called infinitely, which is why console.log is also running continuously.

    To fix this, you need to add a dependency array to useEffect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search