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
CodePudding user response:
Use useEffect(()=>console.log(pokemonTeams), [pokemonTeams])
before this function.
Also, have a look at React Hooks and UseEffect
CodePudding user response:
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
CodePudding user response:
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'))