0

I am very new to React (Building my first application today). I am using an ajax plugin (react-ajax) and so far so good on single JSON calls to an API. However I am struggling to learn how to loop through entires to output multiple results.

    var playersUrl = "/public/index.php/players.json";
    var PlayerList = React.createClass({
    getInitialState: function() {
        return {
            players: ''
        };
    },
    responseHandler: function(err, data){
        this.setState({
            players: data.body.data
        })
    },
    render: function() {
        return (
            React.createElement("ul", {className: "players"},
                React.createElement(Ajax, {url: playersUrl, onResponse: this.responseHandler}),
                this.state.players.map(function (player) {
                  return <li>player.id</li>
                })
            )
        )
    }
});
ReactDOM.render(<PlayerList />, document.getElementById('player-list'));

Basically looking to write an each loop to output some Html populated with the JSON results from the response handler. Thanks a bunch!

{
   "data":[
      {
         "id":"18",
         "firstName":"Graham",
         "gender":{
            "label":"Male",
            "value":"male",
            "selected":true
         },
         "preferred_position":{
            "label":"Attacking",
            "value":"attacking",
            "selected":true
         },
         "dob":{
            "date":"1991-03-25 00:00:00.000000",
            "timezone_type":3,
            "timezone":"UTC"
         },
         "PassingRatingAvg":2.5,
         "ShootingRatingAvg":5,
         "DribblingRatingAvg":3,
         "PaceRatingAvg":2,
         "DefendingRatingAvg":1,
         "OverallRating":13.5,
         "TotalRating":13
      }
   ],
   "meta":{
      "pagination":{
         "total":1,
         "count":1,
         "per_page":100,
         "current_page":1,
         "total_pages":1
      }
   }
}

Edit: Current error "PlayerList.js:18 Uncaught TypeError: this.state.players.map is not a function".

2 Answers 2

1

If I understand your question correctly, your response body may contain multiple records about players. But your responseHandler only handles the the JSON format of one record. Can you describe the structure of your JSON response body? Basically, what you can do is add a players field to your state for multiple records about players, and replace your <h1>{this.state.name}</h1> with something like

this.state.players.map(function (player) {
  return <h1>player.name</h1>
})

And responsehandler should be something like:

function(err, data) {
    this.setState({players: data.body.data})
}

If you are not using es6, you can change that to:

var playersDiv = []
this.state.players.forEach(function(player) {
    playerDiv.push(<h1>player.name</h1>)
})
return playersDiv 
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Yuchen, thanks for the reply, I've added the some of the JSON structure to my original post. Thanks!
Hey Yuchen, I am getting 'Cannot read property 'map' of undefined' for the function you provided, any ideas?
@GrahamDragonbornWilsdon 'Cannot read property 'map' of undefined' means this.state.players is undefined, you didn't set that state yet.
Thanks again for getting back @yuchen I really appreciate it. I've updated the original post with the current code. I am still having an issue setting the state. I am using the latest version of react, react-dom, babel-core 5.8.23 and the latest version of react-ajax.
So when I console log the state in the render this.state.players It logs both the states initial and on initiation of the response handler function. It looks like the state is setting but the map function isn't responding correctly. I've tried forEach too but it's giving me the same error.
0

IRELAND BABY WE DID IT, YEAH

var playersUrl = "/public/index.php/players.json";
var PlayerList = React.createClass({
    getInitialState: function() {
        return {
            players: []
        };
    },
    responseHandler: function(err, data){
        this.setState({players: data.body.data})
    },
    render: function() {
        return (
            React.createElement("ul", {className: "players"},
                React.createElement(Ajax, {url: playersUrl, onResponse: this.responseHandler}),
                this.state.players.map(function (player) {
                    return <li key={player.id}>{player.username}</li>
                })
            )
        )
    }
});
ReactDOM.render(<PlayerList />, document.getElementById('player-list'));

So the main problem was that I didn't define 'players' in the initial state as an array. This stopped the map or forEach functions from firing, I am guessing it's something to do with how React renders? Next up I needed to set some keys on the dynamic children, the identity and state of each child must be maintained across render passes.

Thanks to @yuchen for pointing me in the right direction.

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.