'React fetching multiple get requests
Is there a simpler or more methodical way of fetching multiple requests without having to use a for loop? I basically want to fetch all the information regarding all the Kanto pokemon (151 pokemon), and then extract just the name and front sprite of the pokemon updating my state with the new populated array after fetching all 151 requests. I'm considering doing so using Promise.all but then I have no way of keeping track of the counter for every pokemon.
const [pokemondata,setPokemondata] = useState([]);
useEffect(() => {
const pokemon = []
for (let i = 1;i < 152; i++) {
fetch(`https://pokeapi.co/api/v2/pokemon-form/${i}`)
.then((response) => {
return response.json()
})
.then((data) => {
pokemon.push({name: data.name,sprite: data.sprites.front_default})
})
}
setPokemondata(pokemon)
},[])
Solution 1:[1]
Create an array of promises. I've used Array.from(), but you can also use a for loop and push the promises to an array. Then use Promise.all() to wait for all promises, and set the state when it's ready:
const { useState, useEffect } = React;
const Demo = () => {
const [pokemondata, setPokemondata] = useState([]);
useEffect(() => {
Promise.all(Array.from({ length: 3 }, (_, i) => // change number to 151
fetch(`https://pokeapi.co/api/v2/pokemon-form/${i + 1}`)
.then(res => res.json())
.then(({ name, sprites }) => ({
name,
sprite: sprites.front_default
}))
)).then(setPokemondata)
},[])
return <div>{JSON.stringify(pokemondata)}</div>
}
ReactDOM.render(
<Demo />,
root
)
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ori Drori |
