0

CODE:

var React = require('react');
var User = require('./User.jsx');

var LeaderBoard = React.createClass({

    users: [],

    componentDidMount: function () {    
      var url = 'https://fcctop100.herokuapp.com/api/fccusers/top/alltime'
      var that = this;

      fetch(url)
      .then(function(response) {
        if (response.status >= 400) {
          throw new Error("Bad response from server");
        }
        return response.json();
      })
      .then(function(data) {
        that.setState({ users: data });
      });
    },

    render: function() {

        var usersLeaderboard = this.users.map(function(item) {
            return <User key={item.id} img={item.img} username={item.username} recent={item.recent} alltime={item.alltime} />;
        });

        return (
            <table>
                <tbody>
                    <tr>
                        <th>Avatar</th>
                        <th>Username</th> 
                        <th>30 Days</th>
                        <th>All Time</th>
                    </tr>
                    {usersLeaderboard}
                </tbody>
            </table>
        );
    } 
});

SITUATION:

I am following the FreeCodeCamp curriculum and trying to create a leaderboard with React. Sadly, not all the data renders and I have no errors in the terminal or the Chrome dev tools console.

PROBLEM:

This is what renders on my screen:

enter image description here

No users appear :/

What have I done wrong ?

P.S.: New to React, started learning.

1
  • Instead of this.users.map try this.state.users.map Commented Apr 16, 2017 at 14:54

1 Answer 1

1

You need to updated the LeaderBoard component as you are using this.setState({ users: data }) to set the component state with the user data, but you didn't defined state object with users key. You can do it like this:

var LeaderBoard = React.createClass({
  getInitialState: function () {
   return {
     users: [],
   };
  },

  ...other code
});

Second thing is that in the render method you need to to get the users from state object like this:

render: function() {
  var usersLeaderboard = this.state.users.map(function(item) {
      return <User key={item.id} img={item.img} username={item.username} recent={item.recent} alltime={item.alltime} />;
    });

    return (
     ...other code
    );
}
Sign up to request clarification or add additional context in comments.

Comments

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.