0

I've posted something similar in the past and never really got an answer and I keep running into this problem. Things in my app are working, but I'm not really sure why. I'm using a third-party api to make a simple recipe app. The data I'm passing into my component is displaying as expected, but it's not logging into the console as expected.
Line 20 of App.js is logging what I'd expect (the data received from the api). Line 4 of Recipe.jsx is logging what I'd expect (each item in the recipes array). But line 22 of App.js is coming back as undefined. I would expect that because I setRecipes to 'data', that 'recipes' would log the same as 'data'. Can anyone explain this to me?

import React, { useEffect, useState } from "react";
import "./App.css";
import Recipe from "./Recipe";
import axios from "axios";

function App() {
  const APP_ID = "XXXXXXXX";
  const APP_KEY = "XXXXXXXXXXXXXXXXXXX";
  const url = `https://api.edamam.com/api/recipes/v2?type=public&q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}`;
  const [recipes, setRecipes] = useState([]);
  useEffect(() => {
    getRecipes();
  }, []);
  const getRecipes = async () => {
    const res = await axios(url);
    const data = await res.data.hits;
    console.log(data);
    setRecipes(data);
    console.log(recipes);
  };
  return (
    <div className="App">
      <form className="search-form">
        <input className="search-input" type="text" />
        <button className="search-button" type="submit">
          Search Recipes
        </button>
      </form>
      {recipes &&
        recipes.map((recipe, idX) => <Recipe recipe={recipe} id={idX} />)}
    </div>
  );
}

export default App;
import React from "react";

const Recipe = ({ recipe, id }) => {
  console.log(recipe);
  return (
    <div key={id}>
      <h1>{recipe.recipe.label}</h1>
      <p>{recipe.recipe.calories}</p>
      <img src={recipe.recipe.images.SMALL.url} alt="" />
    </div>
  );
};

export default Recipe;
RRhodes
  • 501
  • 6
  • 19

1 Answers1

0

SetState is asynchronous and may not resolve straightaway. See this part of the docs for more information

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

As you've said, the data coming back is correct, and you've made a call to set state. But the state hasn't resolved by the time you come to the next line where state is consoled out

Steve
  • 122
  • 1
  • 2
  • 9