I am attempting to make many HTTP calls in a component using useEffect and useState to store the results of this http call. I thought I had a basic understanding of how useEffect works but I am confused as to why my code isn't working and therefore must be implementing it wrong.
Here is my useEffect hook code in my dashboard component:
useEffect(() => {
isMounted.current = true;
const fetchData = async () => {
if (survey === null) {
const surveyResponse = await getSurveys('standard');
setSurvey(surveyResponse.data);
}
if (teamInfo === null) {
const teamInfoResponse = await getTeamInfo(user.teamId);
setTeamInfo(teamInfoResponse.data);
}
if (week === null || year === null) {
const weekAndYearResponse = await getWeekAndYear();
setWeek(weekAndYearResponse.data.weekNumber);
setYear(weekAndYearResponse.data.year);
}
if (week && year && !stats) {
const statsResponse = await getTeamSurveyStats(week, year, user.teamId);
setStats(statsResponse.data);
}
};
fetchData();
return () => {
// executed when unmount
isMounted.current = false;
};
}, [survey, teamInfo, week, year, stats, user.teamId]);
I thought that checking to see if the state value I was setting for the return of each call, I could chuck this http call inside a conditional and it would only make the http request on re-render if that variable was null, as I define this using useState(null).
When I check my network tab I see the following:
The first call only runs once which is correct - this is getSurveys the second call runs twice which is incorrect as only needs to run once - this is getTeamInfo the third call runs 5 times which is strange as only needs to run once - this is getWeekAndYear the fourth call runs only once which is correct.
Can anyone see why 2 of these calls are running several times? Thanks