1

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;
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
balu ji
  • 9
  • 1
  • Does this answer your question? [Why is setState in reactjs Async instead of Sync?](https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync) – Kapobajza Aug 27 '22 at 10:31

1 Answers1

1

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

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
  • I want to list the array of value in return like. {trending.map((value)=>

    value

    )}. But due to no value intially it is breaking. how could solve the problem Amila
    – balu ji Aug 27 '22 at 11:01
  • use optional chaining operator(`?.`) -> `{trending?.map((value)=>

    value

    )}`
    – Amila Senadheera Aug 27 '22 at 11:03