Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

769
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!