OiO.lk Blog javascript React useEffect goes in infinite loop while fetching data
javascript

React useEffect goes in infinite loop while fetching data


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.



You need to sign in to view this answers

Exit mobile version