I'm, trying to build a simple Pokemon app using Pokeapi + React-Redux + TS
For those familiar with this API, a basic call for a pokemon list returns an object with pokemon name and a URL with a endpoint to get detailed info
I need to pick both calls (list + each pokemon detailed info) at the same time. What's happening is that (apparently) "list" call resolves ok but does not wait for detail calls to solve
Code here:
async function getDetailedInfo(id: number) {
return await
axios.get(`https://pokeapi.co/api/v2/pokemon/${id}`);
}
export const morePokemon = (url: string) => async (dispatch:
Function) => {
try {
const response = await axios.get(url); //Always resolves properly
const newPokemon: stateInterface['pokemon'] =
response.data.results.map(
(element: { name: string; url: string }) => ({
name: element.name,
id: element.url.split('/')[6],
inTeam: false,
details: {}
})
);
newPokemon.forEach( async (pok, i)=> {
newPokemon[i].details = await getDetailedInfo(pok.id)
console.log(newPokemon[i].details) // REQUIRED DATA LOGED HERE
})
console.log(newPokemon) // REQUIRED DATA LOGED AS WELL
dispatch(nextPokemon(response.data.next));
return dispatch(morePokemonSuccess(newPokemon));
} catch (err) {
return err;
}
};
But, in the component:
function PokemonList({
state,
dispatch,
}: {
state: stateInterface;
dispatch: Function;
}): JSX.Element {
useEffect(() => {
dispatch(morePokemon(state.next));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dispatch]);
const list = state?.pokemon?.map((element: any) => {
console.log(element); // ******** //
return (
<div className="list__item" key={element.id}>
......
If I console log inside state.pokemon.map function "element" I can see that there is a "detail" property with detailed info of each pokemon, BUT if I console.log at the same point "element.detail", it returns an empty object.
With Redux Debugging tools I can see that details is empty, which makes sense of a async issue, but how can I log "elements" and see that "details" property is fulfilled with required data, and if I log "elements.details", show an empty object? Same for logging in "morePokemon" function. This happens only for "getDetailedInfo" function
This is driving me crazy.