phantom phantom - 14 days ago 6
React JSX Question

using data from GET request in react and use in child component

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>
}
})

Answer

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,
       })
    });
}

See the docs.

Comments