Reputation: 11
I'm still having difficulty with my state "pokeData". I'm calling pokeapi and setting the state and am able to obtain 1 level of nested data, anything more and I get an error and my state becomes undefined. Below is a pic of the console and what the data structure shows.
My problem is at this line code: `
<img src={pokeData.sprites.front_default} alt=""/>
`
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const Card = () => {
const [ pokeData, setPokeData ] = useState([]);
useEffect(() => {
axios
.get('https://pokeapi.co/api/v2/pokemon/151')
.then(res => {
setPokeData(res.data);
})
.catch(err => {
console.log(err);
})
}, []);
console.log(pokeData);
return (
<div className="card">
<h1 className="poke-name">{pokeData.name}</h1>
<img src={pokeData.sprites.front_default} alt=""/>
</div>
)
}
export default Card;
Upvotes: 1
Views: 98
Reputation: 878
working example: link - sandbox using optional_chaining
setPokeData will be asynchronous and the data availability in pokeData is going to take some time. Since pokeData's initial value is empty array []
, this {pokeData.sprites.front_default}
would be {[].sprites.front_default}
and you get undefined error.
you could use optional chaining operator (?.) to safely ignore if the key value is not available in the object.
<img src={pokeData?.sprites?.front_default} alt=""/>
ref:
Upvotes: 0
Reputation: 353
Your pokeData
is received via asynchronous action so by the time of rendering, your data may not be set yet.
You can check the availability of your data before actually rendering
{ (pokeData && pokeData.sprites) &&
<img src={pokeData.sprites.front_default} alt=""/>
}
Upvotes: 1