Moritz L.
Moritz L.

Reputation: 177

async fetch triggered three times

I use this in my react app to fetch data from my backend server:

React.useEffect(() => {
    const fetchWidgets = async () => {
      const response = await fetch("http://localhost:1202/data");
      const responseData = await response.json();
      setData(responseData);
      console.log(responseData);
    };
    fetchWidgets();
  });

It fetching data works fine, but the function seems to be triggered three times for some reason. responseData is logged three times.

Upvotes: 1

Views: 309

Answers (2)

Safa Elmalı
Safa Elmalı

Reputation: 79

Use Empty Brackets for the second parameter of useEffect.

React.useEffect(() => {
    const fetchWidgets = async () => {
      const response = await fetch("http://localhost:1202/data");
      const responseData = await response.json();
      setData(responseData);
      console.log(responseData);
    };
    fetchWidgets();
  },[]);

That will ensure the useEffect only runs once.

Upvotes: 0

Mechanic
Mechanic

Reputation: 5380

React.useEffect runs every time after component renders, unless you tell it not by defining a dependency array as its second argument; since you are setting a state inside its body which causes the comonent to re-render, you will see it happens multiple times. to fix the problem you may pass an empty array [] it will only run once after first render and acts like componentDidMount in class components. or add some dependency to run only if the dependencies change;

React.useEffect(() => {
    const fetchWidgets = async () => {
      const response = await fetch("http://localhost:1202/data");
      const responseData = await response.json();
      setData(responseData);
      console.log(responseData);
    };
    fetchWidgets();
},[]);

Upvotes: 2

Related Questions