0

I am making a GET request in my react app that returns team data. I am making this in the parent component and then passing it down to the child Loop component. The GET request is working but it is undefined when it gets to the render function, presumably because my GET request hasn't completed. I have tried to use componentWillMount but I was experiencing the same issue.

Is there anyone out there who can see something obvious i am doing wrong? i am quite new to React.

Please see my code below.

var App = React.createClass({

    getInitialState: function() {
       return {
           teams: []
       }
    },

    componentDidMount: function() {
       $.get(url, function(data) {
           this.state.teams.push(data)
        });
    },

    render: function() {
       console.log(this.state.teams)
          return ( 
             < div >
               < Loop teams={this.state.teams} / >
             < /div>
          )
     }
});

var Loop = React.createClass({
    render: function() {
        var teamList = this.props.teams.map(function(team, index){
            return(
                <h1 key={index}>
                    {team.name}
                </h1 >
             )
        }) return <ul > {teamList} < /ul>
    }
})
  • 1
    You cannot change the `this.state` object directly as you do, **[see here](https://facebook.github.io/react/docs/state-and-lifecycle.html#do-not-modify-state-directly)**. In your case I guess it should be `this.setState({ teams: data })`. – lorenzo-s Nov 18 '16 at 09:58

1 Answers1

2

You're on the right track: the reason why you get undefined is because the request hasn't finished yet.

That's because your code uses this.state which changes the state directly. But your request is asynchronous so you need to use setState, which update state only when the request is done:

componentDidMount: function() {
   $.get(url, function(data) {
       this.setState({
         teams: data,
       })
    }.bind(this));
}

See the docs.

U r s u s
  • 6,680
  • 12
  • 50
  • 88
  • Thats because you need to bind `this` to the callback. `}.bind(this)` at the end of the callback you are passing to the get request will work. If you can, use arrow functions `data =>` – Tiago Engel Nov 18 '16 at 10:14
  • That means the scope of `this` has changed. So you must bind it to the new context. I made an edit. An alternative is using [ES6 arrow functions](http://stackoverflow.com/a/35020509/2794702). – U r s u s Nov 18 '16 at 10:18
  • It's also worth mentioning that `this.state` should be treated as **immutable** so mutating it directly with `this.state.push` should be avoided. _[Referenced from this link](https://facebook.github.io/react/docs/react-component.html) (scroll to bottom)_ – Pineda Nov 18 '16 at 10:19