Reputation: 59
I recently started to learn react. I am making a pokedex app with pokeAPI. On the card I need to get the type of each pokemon. Below is an example of how I get and save pokemon data.
useEffect(() => {
const endpointForPokemonInfo = `${pokemonUrl}`;
fetchPokemon(endpointForPokemonInfo); // eslint-disable-next-line
}, []);
const fetchPokemon = endpointForPokemonInfo => {
fetch(endpointForPokemonInfo)
.then(result => result.json())
.then(result => {
setPokemon([...Pokemon, result.results]);
}, setLoadingForPokemon(false))
.catch(error => console.error("Error:", error));
};
This is example how I display type of pokemon.
{Pokemon &&
Pokemon.map((types, id) => (
<React.Fragment key={id}>
<div
style={{
color: "#333",
padding: 5,
maxWidth: 100,
display: "inline-block"
}}
>
{types.type.name}
</div>
</React.Fragment>
))}
I don’t know what the problem is, but it throws an error.
Uncaught TypeError: Cannot read property 'type' of undefined
at GridCards.js:50
at Array.map (<anonymous>)
at GridCards (GridCards.js:46)
at renderWithHooks (react-dom.development.js:14803)
at updateFunctionComponent (react-dom.development.js:17034)
at beginWork (react-dom.development.js:18610)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at beginWork$1 (react-dom.development.js:23203)
at performUnitOfWork (react-dom.development.js:22154)
at workLoopSync (react-dom.development.js:22130)
at performSyncWorkOnRoot (react-dom.development.js:21756)
at react-dom.development.js:11089
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
at flushSyncCallbackQueue (react-dom.development.js:11072)
at scheduleUpdateOnFiber (react-dom.development.js:21199)
at dispatchAction (react-dom.development.js:15660)
at GridCards.js:23
If I console.log(result)
or console.log(...Pokemon)
, console shows this result
Upvotes: 3
Views: 2750
Reputation: 14433
From the results structure, it is clear that Pokemon.types
is also an array, so you need to use .map()
once more:
{
Pokemon &&
Pokemon.map((types, id) => (
<React.Fragment key={id}>
{
types.map((currType, typeId) => (
<div
key={typeId}
style={{
color: "#333",
padding: 5,
maxWidth: 100,
display: "inline-block"
}}
>
{currType.type.name}
</div>
))
}
</React.Fragment>
))
}
Upvotes: 1
Reputation: 120
setPokemon([...Pokemon, result.types]);
should set Pokemon: [result.types]
which should set Pokemon as the array result.types
you'll have to iterate with the map function as you have
{Pokemon &&
Pokemon.map((types, id) => (
<React.Fragment key={id}>
<div
style={{
color: "#333",
padding: 5,
maxWidth: 100,
display: "inline-block"
}}
>
{type.name}
</div>
</React.Fragment>
))}
should iterate and map each type.
Upvotes: 0