Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

768
Vistas
UseState is not updating inside await method

What my code is trying to do is get an array of objects by doing multiple get requests. I am then pushing the response.data to the setPokemonTeam variable and it is not working. Everytime I log the array in console it appears empty.

const [pokemonTeam, setPokemonTeam] = useState([]);

const generatePokemon = async () => {
    setPokemonTeam([]);
    const pokemonIDs = [];

    do {
      const randomID = Math.floor(Math.random() * 121);

      if (!pokemonIDs.includes(randomID)) {
        pokemonIDs.push(randomID);
      }
    } while (pokemonIDs.length < 6); //max 6 pokemon only
    let promises = [];
    for (var i = 0; i < pokemonIDs.length; i++) {
      promises.push(
        await axios
          .get(`https://pokeapi.co/api/v2/pokemon/${pokemonIDs[i]}/`)
          .then((res) => {
            setPokemonTeam([...pokemonTeam, res.data]);
            console.log(res.data);
            console.log(pokemonTeam);
          })
          .catch((err) => {
            console.log(err);
          })
      );
    }
    Promise.all(promises);
    console.log(pokemonTeam);
  };

my console is getting the correct data but it is not updating the pokemonTeam array.

This is what my console looks like

This is the code with each line included

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

Use useEffect(()=>console.log(pokemonTeams), [pokemonTeams]) before this function.

Also, have a look at React Hooks and UseEffect

about 4 years ago · Santiago Gelvez Denunciar

0

Please check if this is helpful for you.

import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

function App() {
  const [pokemonTeam, setPokemonTeam] = useState([])
  let pokemonIDs = []
  do {
    const randomID = Math.floor(Math.random() * 121)
    if (!pokemonIDs.includes(randomID)) {
      pokemonIDs.push(randomID)
    }
  } while (pokemonIDs.length < 6)

  useEffect(() => {
    for (var i = 0; i < pokemonIDs.length; i++) {
      axios
        .get(`https://pokeapi.co/api/v2/pokemon/${pokemonIDs[i]}`)
        .then((res) => {
          setPokemonTeam((prev) => [...prev, res.data])
        })
        .catch((err) => {
          console.log(err)
        })
    }
  }, [])
  console.log(pokemonTeam)
  return 'Hello'
}

ReactDOM.render(<App />, document.getElementById('root'))

about 4 years ago · Santiago Gelvez Denunciar

0

The default value of pokemonTeam is "[]" line 1 (set in useState):

const [pokemonTeam, setPokemonTeam] = useState([]);

You need to remove the line 3

setPokemonTeam([]);

To avoid reloading your component before the asynchronous request is finished executing

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda