Sachin Karia Sachin Karia - 1 month ago 7
React JSX Question

reactjs render() not triggered after promise resolves this.setState is re-assigned

I have a function below which sets an InitialState and then makes an api call with componentWillMount and fetchData to assign the data this.state. However when this.setState() is done the render function does not triggered with the new this.state data my function is below:

var Home = React.createClass({
getInitialState: function() {
return {
city: '',
weather: '',
temperature: 0,
humidity: 0,
wind: 0,
}
},
fetchData: function() {
apiHelpers.getCityInfo()
.then(function (response){
this.setState({ data: response
})
}.bind(this))
},
componentWillMount: function(){
this.fetchData();
},
render: function () {
return (
<div className="container">
<Cities data={this.state.data} />
</div>
)
}
});

Answer

There is no data on initial state. Change your code as-

fetchData: function() {
    apiHelpers.getCityInfo()
     .then(function (response){
      this.setState({
          city: response.city,
          weather: response.weather,
          temperature: response.temperature,
          humidity: response.humidity,
          wind: response.wind,
       })
    }.bind(this))
  },

expecting your api response contain object as city, weather, ... so on..