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.
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