Home > Back-end >  Why is use effect rendering the page twice?
Why is use effect rendering the page twice?

Time:02-11

I have data I'm trying to fetch and use with the code below, however when I am logging the value of records I get an empty array first and my fetched object second. Because of this, I'm unable to access the object's information in my app.


  const [records, setRecords] = useState([]);

 useEffect(() => {
    async function getRecords() {
      const response = await fetch(`http://localhost:5000/record`);

      if (!response.ok) {
        const message = `An error occurred: ${response.statusText}`;
        window.alert(message);
        return;
      }

      const records = await response.json();
      setRecords(records);
    }

    getRecords();

    return;
  }, []);

  console.log(records);

CodePudding user response:

The first render triggers the effect.

The effect calls setRecords which triggers the second render.

You need to write your display logic so it can account for records defaulting to an empty array.

  • Related