Tanzeel
Tanzeel

Reputation: 4998

TypeError: items is undefined while reading a json using fetch in reactjs

This is the first time I'm working with APIs using ReactJS. I know the basics of reactjs pretty well but I'm unable to read the response. I've a json response from youtube apienter image description here.

Initially i got

TypeError: items.map is not a function.

But then i realized that i might be getting an Object and not an array. I solved the problem by items: json.statistics. But now I'm getting other error i.e

TypeError: items is undefined

I just want to fetch 3 information viz viewCount, subscriberCount and videoCount. I've written this code

import React, {Component} from 'react';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
           items: [],
           isLoaded: false
        }
    }

    componentDidMount() {
        fetch('https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCOYqNBjmWF8j-PzI7ZPjt_w&key=AIzaSyAMeZQW6sUQgLdDTnMVeokfbcFcT2A9SuA')
        .then(res => res.json())
        .then(json => {
            this.setState({
                isLoaded: true,
                items: json.statistics
            })
        });
    }

    render() {
        var {isLoaded, items} = this.state;
        if(!isLoaded) {
              return (<div>Loading...</div>)
        }
        else {
            return (
                <div>
                   <ul>
                      {
                         items.map(item => (
                           <li key={item.id}>
                              Total views: {item.viewCount} 
                              Total subscribers: {item.subscriberCount}
                              Total videos: {item.videoCount}
                           </li>
                        ))}
                    </ul>
                </div>
            )
          }
      }
   }

    export default App;

Upvotes: 2

Views: 2692

Answers (2)

AxelJunes
AxelJunes

Reputation: 656

It seems like the problem is in your setState(). Try something like this:

import React, { Component } from "react";
import "./styles.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false
    };
  }

  componentDidMount() {
    fetch(
      "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCOYqNBjmWF8j-PzI7ZPjt_w&key=AIzaSyAMeZQW6sUQgLdDTnMVeokfbcFcT2A9SuA"
    )
      .then(res => res.json())
      .then(({ items }) => {
        this.setState({
          isLoaded: true,
          items
        });
      });
  }

  render() {
    var { isLoaded, items } = this.state;
    if (!isLoaded) return <div>Loading...</div>;
    return (
      <div>
        <ul>
          {items.map(({ id, statistics }) => (
            <li key={id}>
              Total views: {statistics.viewCount}
              Total subscribers: {statistics.subscriberCount}
              Total videos: {statistics.videoCount}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

Also, you don't need an if else statement if you have a return. Either use a ternary operator or just remove the else.

Here's the sandbox if you want to take a look at it. Let me know if it helps.

Upvotes: 2

ravibagul91
ravibagul91

Reputation: 20755

You are getting data in items array, you need to set json.items in state,

this.setState({
    isLoaded: true,
    items: json.items
})

And then you will get statistics object data,

{
    items.map(item => (
        <li key={item.id}>
          Total views: {item.statistics.viewCount} 
          Total subscribers: {item.statistics.subscriberCount}
          Total videos: {item.statistics.videoCount}
        </li>
    ))
}

Demo

Upvotes: 1

Related Questions