-1

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?

Maven
  • 14,587
  • 42
  • 113
  • 174
  • 1
    `loadData()` should be called within an effect hook – Phil Jul 17 '23 at 04:40
  • 1
    The component function gets called whenever component needs to be re-rendered - it's state or state of its parent changes. You can use useEffect to call the function once (or specify it's dependencies). To keep the result, use useState hook. – Lesiak Jul 17 '23 at 04:43

1 Answers1

1

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

sojin
  • 2,158
  • 1
  • 10
  • 18