So I'm building just a small web app that takes data from the giphy API and then displays it. Bear with me. This is a long one.
export const fetchTrending = async () => {
try {
const {data:{data}} = await axios.get('https://api.giphy.com/v1/gifs/trending?api_key=4A40i9pS4hOK6N3f77WYflnhZe93UIB4&limit=5&rating=g')
return data;
} catch (err) {
console.log(err);
}
}
Then the data goes to app.js
class App extends React.Component{
state={
data:[{}]
}
async componentDidMount(){
const response = await fetchTrending();
this.setState({data:response})
}
render(){
const {data} = this.state;
return (
<div>
<NavBar />
<img className={styles.ad1} src="https://media.giphy.com/headers/2020-07-27-05-1595862312/NBA_BANNER_HP.gif" />
<Trending data={data} />
</div>
)
}
}
From there to its final destination.
export const Trending = ({data:data}) => {
const images = data[0].images;
console.log(images);
return (
<div>
<h2 className={styles.trending}>TRENDING Gifs</h2>
</div>
);
};
The API which is here https://api.giphy.com/v1/gifs/trending?api_key=4A40i9pS4hOK6N3f77WYflnhZe93UIB4&limit=5&rating=g consists of data, meta and pagination. All I want is the url which is in downsized in the images object of the each data object. But each time I try to destructure it. It gives me the undefined object error no matter what I try. Again, apologies for the long description. If I hadn't wrote all of this you wouldn't understand.
The error I'm getting is this.
Cannot destructure property 'downsized' of 'images' as it is undefined.
Trending
/src/Components/Trending/Trending.jsx:8
5 | export const Trending = ({data:data}) => {
6 |
7 | const images = data[0].images;
> 8 | const {downsized} = images;
9 | console.log(downsized);
10 |
also getting an undefined object . Why????
Your initial state is empty:
Before the giphy api is called and the result is set as the state (it's an asynchronous operation), this object is passed to the
Trending
componentInside the Trending component, you access the property
images
of the first element:But your initial data is
[{}]
, sodata[0] = {}
and thereforedata[0].images
is undefined. Then, you try to access the propertydownsized
on an undefined item!You need to check if images exists before trying to access the downsized property