I am getting Too many re-renders error while setting data in a hook after fetching data from an API. on line setCustomData(formData);
At first I thought it's because of rerendering and useEffect being called multiple times but I have inculdes the empty array for that so that useEffect renders only once.
So I am not sure what's going wrong here. I would really appreciate your help.
const [numOfApplications, setNumOfApplications] = useState(0);
const [customData, setCustomData] = useState();
React.useEffect(() => {
if (props.user.attributes["custom:role"] !== "Parent") {
const campusId = props.user.attributes["custom:campusId"];
const orgId = props.user.attributes["custom:orgId"];
fetchCampusDetails(orgId, campusId)
.then((res) => {
console.log("result for campus details");
console.log(res.data.customData);
const formData = JSON.parse(res.data.customData.formData);
setCustomData(formData);
getAllCampusAnalytics(campusId)
.then((result) => {
const data = result.data.classes.all;
const numOfApps = data.total - data.Draft;
setNumOfApplications(numOfApps);
})
.catch((err) => {
console.log(err);
});
})
.catch((err) => {
console.log(err);
});
}
if (props.user.attributes["custom:role"] === "Parent") {
if (!localStorage.getItem("orgList"))
getAllCampus().then((res: any) => {
console.log(res);
res.data.map(async (menu: any) => {
const name = menu.orgName.replace(/\s/g, "_");
const formDataUrl = JSON.parse(
menu.campusList[0].customData.formData
);
const formData = await schoolForm(name, formDataUrl);
if (cookie.type) {
localStorage.setItem("type", cookie.type);
} else localStorage.setItem("type", "1");
});
setOrganisationList(res.data);
localStorage.setItem("orgList", JSON.stringify(res.data));
if (
cookie.school &&
res.data.filter((org: any) => {
if (org.orgName === cookie.school.replace(/_/g, " ")) return org;
else return null;
}).length === 0
)
removeCookie("school", {path: "/"});
});
}
}, []);
Firstly you should move the api calls out into their own function and call the function from within useEffect.
The reason its re-rendering is probably to do with the parent. If the parent re-renders, so does the child unless you use memo or something like that. Difficult to say without seeing the parent code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.