reactjsgiphy-api

Getting an undefined object before the object is populated


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 | 

enter image description here

also getting an undefined object . Why????


Solution

  • Your initial state is empty:

    state={
        data:[{}]
      }
    

    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 component

    <Trending data={data} />
    

    Inside the Trending component, you access the property images of the first element:

    const images = data[0].images;
    const {downsized} = images;
    

    But your initial data is [{}], so data[0] = {} and therefore data[0].images is undefined. Then, you try to access the property downsized on an undefined item!

    const data = [{}}
    
    data[0]; // => {}
    data[0].images; // => undefined
    data[0].images.downsized // => ERROR!
    

    You need to check if images exists before trying to access the downsized property

    const downsized = images ? images.downsized : null