Search code examples
node.jsreactjsaxiosuse-effectmern

Axios get request inside useEffect gives infinite loop


Calling axios get request inside useEffect results in infinite loop

useEffect(() => {
    get();
});

const get = async () => {
    await axios.get("http://localhost:5001/events/get").then((res) => {
        setEvents(res.data);
    });
    console.log(events);
};

enter image description here

but if i give dependency as second argument, then only empty array is returned 2 times.

const [events, setEvents] = useState([]);

useEffect(() => {
    get();
}, []);

const get = async () => {
    await axios.get("http://localhost:5001/events/get").then((res) => {
        setEvents(res.data);
    });
    console.log(events);
};

enter image description here

How to resolve this?


Solution

  • The hook useState() returns a function to mutate the state, in this case setEvents. This mutation function is asynchronous in nature meaning the state does not update immediately as it waits for the component to re-render.

    When calling console.log statement right after the setEvents method, it will print out an outdated copy of the events state and thus you see the empty array.

    In order to confirm if your network request properly works, try logging the value of events in a separate useEffect hook with events as the dependency. This will run that useEffect block as soon as events state updates after a re-render:

    // Make the network request
    useEffect(() => {
        get();
    }, []);
    
    // Check if the events state updated
    useEffect(() => {
        console.log(events);  // Move the console log here
    }, [events]);             // Add `events` as a dependency
    
    const get = async () => {
        await axios.get("http://localhost:5001/events/get").then((res) => {
            setEvents(res.data);
        });
        console.log(events);
    };