Why setState return empty in react on its first time. Whenever changes made it showing the result

Viewed 28

I am new to react.I have trying to set the value using useState. But on first time it is not showing. But on next loading it shows the value.

    import { useEffect, useState } from 'react';
    
    
    const Home = () => {
      
      const [trendingFood, setTrendingFood] = useState([]);
      
      useEffect(() => {
        fectedData();
      }, [])
    
      const fectedData = async() => {
        const foodData =await fetch(`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_TEMP_KEY}&number=10`);
        const resp =await foodData.json();
        setTrendingFood(resp);
        console.log(resp)
        console.log(trendingFood);
      }
    
    
      return <div>Home</div>
    };
    
    export default Home;
1 Answers

The setState call is asynchronous and will take time to update. To see the updated value you need to move the second console.log to the component level. When each time it rerenders(i.e when the state changes) you can see the value:

import { useEffect, useState } from "react";

const Home = () => {
  const [trendingFood, setTrendingFood] = useState([]);

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

  const fectedData = async () => {
    const foodData = await fetch(
      `https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_TEMP_KEY}&number=10`
    );
    const resp = await foodData.json();
    setTrendingFood(resp);
    console.log("a: ", resp);
  };

  console.log("b: ", trendingFood);

  return <div>Home</div>;
};

export default Home;

Demo:

Edit tender-brook-os4rci

Related