Home > Mobile >  Axios get request inside useEffect gives infinite loop
Axios get request inside useEffect gives infinite loop

Time:07-12

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?

CodePudding user response:

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);
};

CodePudding user response:

I expect you are using React 18. In new React 18 for adding some new functionality in future they have designed such that in strict mode useEffect will run twice. You can either stop running the app in strict mode or Follow this one.

Another Option Here

And as you mentioned about the dependency array, so you must be knowing how to avoid the infinite execution

CodePudding user response:

Before coming to any solutions I would like to suggest two chores in order to debug the problem.

Using try-catch block to catch any errors in the api itself

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

Try defining the get() function inside the useEffect()

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

useEffect(() => {
const get = async () => {
try{
    await axios.get("http://localhost:5001/events/get").then((res) => {
        setEvents(res.data);
    });
    console.log(events);
} catch (e){
console.error(e)
}
};
 get();
}, []);

You may share yout findings after doing that and it may help us in debugging the probllem.

Thank you!!!

  • Related