Reputation: 19
I'm fetching data from PokeAPI to my personal project and I need to fetch twice, first to get a Pokemon list which give me a list of Pokemon name with the range I specify, in this case 0 to 20 and then I map this data to fetch specific data for each of these 20 Pokemon but it is not working.
The fetching process is working, I can see everything on console if I set console.log(res), but I can't push data into the products variable, how should I handle it?
export const getStaticProps: GetStaticProps = async () => {
let products: any = [];
const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20&offset=0');
const list = await response.json();
list.results.map((e: any) => {
fetch(`https://pokeapi.co/api/v2/pokemon/${e.name}`)
.then(res => res.json())
.then(res => {
products.push(res);
console.log(e.name);
})
})
return {
props: {products,},
}
}
I already tried async/await method, tried wrap map into an IIFE, wrap everything in try/catch but nothing of this work, I can return the first fetch (list) but the second one returns empty array.
Upvotes: 0
Views: 67
Reputation: 813
RE what @ivanatias said
You want to first make all the promises, then await their result and return.
I would also recommend adding a catch here in case they fail.
export const getStaticProps: GetStaticProps = async () => {
const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20&offset=0');
const list = await response.json();
const promises = list.results.map((pokemon: any) => {
return fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon.name}`).then(res => res.json());
})
const pokemon = await Promise.all(promises);
return {
props: {
pokemon
}
}
}
Upvotes: 1