Exceeding callstack depth
Unanswered
Spotted Redshank posted this in #help-forum
Spotted RedshankOP
Currently I have a function like this but it keeps calling it self. The problem is I need to update the total and other 2 fields everytime a sub variable of "regels" is updated. Any other way to do this? Because currently it's just looping
useEffect(() => {
if (aantalRegels !== null) {
setRegels(oldRegels => {
// Create a copy of the oldRegels array
let newRegels = oldRegels ? [...oldRegels] : [];
// If aantalRegels is greater than the current length, add new rows
while (newRegels.length < aantalRegels) {
newRegels.push({ aantal: null, omschrijving: null, bedrag: null, totaal: null, btw: null });
}
// If aantalRegels is less than the current length, remove extra rows
newRegels = newRegels.slice(0, aantalRegels);
return newRegels;
});
}
}, [aantalRegels]);
useEffect(() => {
if (regels !== null) {
// Calculate the total cost of each row
setRegels(oldRegels => {
let newRegels = oldRegels ? [...oldRegels] : [];
newRegels.forEach((regel: any) => {
if (!regel.aantal || !regel.bedrag) regel.totaal = null;
if (regel.aantal && regel.bedrag) {
regel.totaal = regel.aantal * regel.bedrag;
}
});
return newRegels;
});
setSubTotalCost(Math.round(regels.reduce((acc, regel) => acc + (regel.totaal || 0), 0)));
setBtwCost(Math.round(regels.reduce((acc, regel) => acc + ((regel.totaal || 0) * (regel.btw || 0) / 100), 0)));
setTotalCost(Math.round((subTotalCost || 0) + (btwCost || 0)));
}
}, [regels]);