Reputation: 565
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>
)
}
});
Upvotes: 2
Views: 632
Reputation: 282030
As per the react docs
componentWillMount
is Invoked once, both on the client and server
, immediately before the initial rendering occurs. If you call setState within this method, render()
will see the updated state and will be executed only once
despite the state change.
To solve this issue, instead of componentWillMount
use componentDidMount
. Since you are updating the response in state variable data
, define it first and then no need of defining the other state variables just pass data on to the child component
and update the state as you are doing now.
var Home = React.createClass({
getInitialState: function() {
return {
data: ''
}
},
fetchData: function() {
apiHelpers.getCityInfo()
.then(function (response){
this.setState({ data: response
})
}.bind(this))
},
componentDidMount: function(){
this.fetchData();
},
render: function () {
return (
<div className="container">
<Cities data={this.state.data} />
</div>
)
}
});
Upvotes: 0
Reputation: 4526
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..
Upvotes: 1