Reputation: 1232
I cant access the object what I want. Some kinda object exist in this API. First I try to access poke name it's the easy one!
import React, { useState, useEffect } from "react";
import "./App.css";
import { Link } from "react-router-dom";
function PokemonList() {
useEffect(() => {
fetchPokemon();
}, []); // square bracket means this only gone run when the component mounts
const [pokemon, setPokemon] = useState([]);
const fetchPokemon = async () => {
const data = await fetch(`https://pokeapi.co/api/v2/pokemon/3/`);
const pokemon = await data.json();
console.log(pokemon);
setPokemon(pokemon);
I fetch the data inside of pokemon
variable and then
return(
<h1> {pokemon.name} </h1>
)
Success!
Now try to add types
this is the content from pokemon object
<div>
{pokemon.types.map(type => {
return <h1>{type.type.name}</h1>
})}
</div>
I write that code but not working. I see that error message
So I can't react that infos.
By the way, I want to put the images on the screen.
It's kinda different from the types object (I just mention that in the first pic) sprites
object doesn't exist like 0
, 1
nest object. We can directly see back_default
(A nested object under sprites object) So that's examples, are that the same thing or is that really different example between that.
I am started the learn js, react. I hope you will help me, guys. I am stuck help me in that hole! pls :(
Btw, I found some usages for this API.
video link (time 33:44) = https://www.youtube.com/watch?v=HaEB0vdxpdg
Why he uses in the first mention map
function and use the [0]
that thing (I don't understand what does it meant) in the second mention. Pls explanation.
When I add the empty object variable it's worked. -Thanks @AntoineFrau-
But When I deleted the nested items the project is still working. I was thought, It will break and stop working but It's working both of those ways. What is the explanation about this situation?
Upvotes: 2
Views: 1461
Reputation: 712
It's caused by the fact that, React will render your component even if pokemon
is undefined
. So if you try to use map()
function of an undefined
variable it will crash.
One solution will be to initialized your Pokemon variable with a default object:
const [pokemon, setPokemon] = useState({
"height": 0,
"id": 0,
"name": "",
"sprites": {
"default": ""
}
"types": [
{
"slot": 0,
"type": {
"name": "",
"url": ""
}
}
]
});
<div>
{
pokemon.types.map(type => {
return <h1>{type.type.name}</h1>
})
}
</div>
Like that it will print nothing instead of crash.
PS: He use in the video pokemon.abilities[0]
cause I guess he just want to show the first ability of the Pokemon.
If you want you could also create a variable, which will block the render of your component if the data hasn't been loaded yet : https://stackoverflow.com/a/47850151/6809926
Upvotes: 1