0

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;
Jay Jay
  • 33
  • 8
  • Can you please put your response json here, that will give more clarity – Asutosh Jul 31 '20 at 09:48
  • [link](https://api.giphy.com/v1/gifs/search?q=ryan+gosling&api_key=rYJ5AxF8DXFqeX8ub81fbuje3J12lrh6&limit=3) the data[0] in this link :) – Jay Jay Jul 31 '20 at 09:55
  • @Asutosh Thank you for your response it really helped me and I understood better, but why did you deleted the post? – Jay Jay Jul 31 '20 at 10:33
  • You are welcome, I have added it back, you may upvote and mark it as answer if you find it helpful – Asutosh Jul 31 '20 at 10:38
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Jul 31 '20 at 11:22

5 Answers5

1

Try to console.log data like:

console.log(
      this.state.myGif.data
        ? this.state.myGif.data[0]
        : "data is not downloaded yet"
    );
macborowy
  • 1,474
  • 10
  • 13
1

It's because when the first time the component is rendered, this.state.myGif.data does not exist, because the initial state of the myGif is just empty. You should check if the data is loaded ...

console.log(this.state.myGif.data ? this.state.myGif.data[0] : "Loading •••");
Ryuko
  • 377
  • 1
  • 13
1

You don't need json().

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

Then in your render function you can console.log(this.state) to see your entire state. It's an array of objects so you'll need to map it out if you want to display all of them. You can map like this :

this.state.data.map((item,i) => <li key={i}>Test</li>)

Since data in your state may be undefined on the first render. You'll want to set a default value of [] for this.state.data

If you want to display the first one you can say this.state && this.state[0].type

Justsolarry
  • 302
  • 1
  • 9
0

Your fetch and setState calls are both asynchronous. While it is fetching your render will already be called.

One way to fix this is to check for the current state e.g.

 render() {
        this.state.myGif && console.log(this.state.myGif.data[0]);
        return (
            <div>
                <h1>This is </h1>
            </div>
        );
    }
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

import React, { Component } from 'react';

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

        this.state = {
            myGif: {data:["Image is getting Loaded"]},
        };
    }

    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;
Asutosh
  • 1,775
  • 2
  • 15
  • 22