Mando
Mando

Reputation: 31

endless request to back-end using useEffect hook React

I'm trying to make a a request to my back-end so when my component loads it can receive some data to render.

the problem is that the application goes in an infinite loop of requests that consumes resources.

what am I doing wrong?

  useEffect(() => {
    Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
        const peopleArray = [];
        for (let key in response.data) {
          peopleArray.push({ ...response.data[key] });
        }
        setPeople(peopleArray);
      });
  });

Upvotes: 0

Views: 49

Answers (2)

Michele Cerruto
Michele Cerruto

Reputation: 434

Check the Documentation or check this example w3school

Only run the effect on the initial render:

useEffect(() => {
 Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
    const peopleArray = [];
    for (let key in response.data) {
      peopleArray.push({ ...response.data[key] });
    }
    setPeople(peopleArray);
 });
}, []); // <- add empty brackets here

Upvotes: 0

Mina
Mina

Reputation: 17224

You need to an array of dependences to useEffect, to only run on the component mounted or any of these dependencies change. as without an array of dependences, it will run with each render, which will cause an infinite loop.

      useEffect(() => {
    Axios.post("http://localhost:3005/people", {UUID}).then((response) => {
        const peopleArray = [];
        for (let key in response.data) {
          peopleArray.push({ ...response.data[key] });
        }
        setPeople(peopleArray);
      });
  }, []);

Upvotes: 1

Related Questions