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.