October 21, 2024
Chicago 12, Melborne City, USA
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

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video