I have a react page with a function to fetch data from API in a loop. The loop terminates when a certain condition is met. Till here everything keeps working as expected.
export default function Data() {
...
...
needMore = true
var loadData = async () => {
...
while (needMore) {
var result = await fetch('http://localhost:6000/api/data');
dataRow = await result.json();
addItems(offset, dataRow);
if (dataRow.length < bacthSize) {
...
needMore = false
break;
}
};
console.log("Completed.");
}
loadData();
return (
<div className="ag-theme-balham" style={{ width: '100%' }}>
<Stack spacing={2}>
<AgGridReact
...
defaultColDef={defaultColDef} />
</Stack>
</div>
);
}
However, the issue is that the function loadData repeatedly keeps getting called hence creating a indefinite loop.
I can see the complete data has been fetched once and in console I can also see Completed. which I am logging, but immediately that the function gets called again, which I am not sure why and how can I stop this?
>Solution :
Yes, that’s how react works. when you call loadData it will run the function and addItems will update the state. updating state will re-render the component and it will again call load data.
It will execute from the beginning of the component to the end.
You need to use React lifecycle hook – useEffect.
useEffect(()=> {
loaddata()
}, [])
the second argument of useEffect is its dependencies.
check this link for detailed doc
react useEffect