javascriptreactjsobjectsetstategiphy

Error while indexing data from this.setState()


I am creating a GIF search web app with the GIPHY API and react.

After I fetch the data from the API, I can index the data console.log(json.data[0])

.then((json) => {
      console.log(json.data[0]);
      this.setState({ myGif: json });
});

But when I set my state to the JSON file and I try to index the data console.log(this.state.myGif.data[0]) I get an error

TypeError: Cannot read property “0” from undefined

    render() {
        console.log(this.state.myGif.data[0]);
        return (
            <div>
                <h1>This is </h1>
            </div>
        );
    }

I would really appreciate getting a response

Below is the full code of the component

import React, { Component } from 'react';

export class Content extends Component {
    constructor(props) {
        super(props);

        this.state = {
            myGif: {},
        };
    }

    componentDidMount() {
        const api_key = 'rYJ5AxF8DXFqeX8ub81fbuje3J12lrh6';
        fetch(
            `http://api.giphy.com/v1/gifs/search?q=ryan+gosling&api_key=${api_key}&limit=3`
        )
            .then((response) => response.json())
            .then((json) => {
                console.log(json.data[0]);
                this.setState({ myGif: json });     
            });
    }

    render() {
        console.log(this.state.myGif.data[0]);
        return (
            <div>
                <h1>This is </h1>
            </div>
        );
    }
}

export default Content;

Solution

  • Try to console.log data like:

    console.log(
          this.state.myGif.data
            ? this.state.myGif.data[0]
            : "data is not downloaded yet"
        );