Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React keeps calling a function repeatedly

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading