ChuChu
ChuChu

Reputation: 359

Fetching data from API failed

I am testing out the fetch API in React but it doesn't display anything and keeps loading... I'm not sure where i did wrong. Did the server just fail to send data back?

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

    const API_30 = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';

    class App extends Component {
      constructor(props){
        super(props);
        this.state = {campers: []};
        }
      componentDidMount() {
        fetch(API_30)
          .then(response => response.json())
          .then(data => this.setState({ campers: data.campers })
          );

      }

      render() {
    if(!this.state.campers){return <p>Loading...</p>}
        return (
         <div className="App">
            <h1 className="Table-header">FreeCodeCamp Leaderboard</h1>
           {this.state.campers.map((camper) => 
             <div>{camper.username}</div>
           )

           }

              </div>);
      }
    }

    export default App;

Upvotes: 0

Views: 51

Answers (1)

illiteratewriter
illiteratewriter

Reputation: 4323

fetch(API_30)
      .then(response => response.json())
      .then(data => this.setState({ campers: data })
      );

It is not data.campers it was just data.

You can see the data that is returned from the api by console.loging the data.

if you do

fetch(API_30)
      .then(response => response.json())
      .then(data => console.log(data)
      );

you can see in the console that the data is already an array.

Upvotes: 1

Related Questions