I am trying to add multiple objects to a state array using a forEach loop:
const App = () => {
const [pokemon, setPokemon] = useState([]);
axios.get('https://pokeapi.co/api/v2/pokemon') // Gives me 20 pokemon
.then(res => {
res.data.results.map(p => p.url).forEach(url => { // Loops over endpoints of pokemon
axios.get(url)
.then(response => {
setPokemon(response.data)
})
});
})
}
As you can probably guess, only the last item from the forEach loop is shown when I console.log pokemon as it's the last one to be set in the state.
The api I'm working with: https://pokeapi.co/.
I start with making a call to https://pokeapi.co/api/v2/pokemon which gives me 20 pokemon, each pokemon object comes with an endpoint to get more information about it and it's the information from these endpoints I want to store as objects in the state.
Thanks for any help, if you know of a better way I can do this feel free to let me know.