2

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;
5
  • Please clarify what the 'other error' is that you're getting so the community can help Commented Aug 14, 2019 at 11:05
  • ok. edited that part. plz help. Commented Aug 14, 2019 at 11:07
  • Have you tried json.items.statistics? Commented Aug 14, 2019 at 11:12
  • items is an array and access it with index Commented Aug 14, 2019 at 11:13
  • @caladeve. yes. myitems: json.items.statistics. But still i'm getting that error. I even changed the name of my variable so that it doesn't coincide with any other varibale of json response. Commented Aug 14, 2019 at 11:15

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Its working perfectly. thanks. So I've to use {statistics} inside map. What difference will it make btw?
statistics object don't have id, this code will give warning for unique key.
You're right. I've updated the answer so that it takes the id from items.
@Tanzeel Using { statistics } in this case is the same as using items.statistics, because you're mapping over the items array. It's called destructuring in ES6. Check out this article which explains it very well.
1

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

1 Comment

oh. I'm so sorry I was either using Total views: {item.viewCount} or Total views: {statistics.viewCount} . I didn't realize that it has to be Total views: {item.statistics.viewCount}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.