It's my first stackoverflow querstion so be gentle for me 😅
I'am making pokedex app with react query and fetch but I have problem with returning array of my pokemons.
I'm trying to fetch a pokeApi which returns an array of results consisting of objects with another url. Then I try to map trough results array and fetch url for individual pokemon then push it to the arr variable. In the end, I'am returning arr which is not readable.
How to properly push data to arr in map?
What i'am doing wrong? Is there solution?
const fetchData = async (key) => {
const data = await fetch(`https://pokeapi.co/api/v2/pokemon`)
.then((res) => res.json())
.then((data) => {
return data;
});
const arr = [];
data.results.map((item) => {
return fetch(item.url)
.then((res) => res.json())
.then((data) => {
arr.push(data);
});
});
return arr;
};
const { isLoading, data } = useQuery("pokemons", fetchData, {
refetchOnWindowFocus: false
});
if (isLoading) return <div>loading...</div>;
console.log(data); // cant read
return <div>Data loaded</div>;
https://codesandbox.io/s/strange-pond-wz4ws?fontsize=14&hidenavigation=1&theme=dark
awaitthe response but you do notawaitthe parsing of json which is also async. In general you should not mixawaitwith.then(). Use one or the other. Also inside of yourmap()callback you are returning aPromiseinstead of an actual result asfetch()is async.