Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
How does useState set variables?

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;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda