I'm having an issue with React state. It receives an array of objects and it's being set properly in state, but then function finishes it shows that state is empty. Can anyone explain this behaviour?
componentDidMount() {
this.getWeather();
this.getForecast();
this.setState({location: ''});
}
getWeather() {
if (this.state.location === "") {
this.setState({error: 'Please enter something'});
} else {
OpenWeather.getWeather(this.state.location).then(result => {
if (result.cod === "404") {
this.setState({error: 'City not found'});
} else if (result.cod === 200) {
this.setState({error: ''});
this.setState({weather: result});
} else {
this.setState({error: 'Server error'});
}
});
}
}
getForecast() {
OpenWeather.getForecast(this.state.location).then(forecast => {
console.log("Returned forecast:");
console.log(forecast);
this.setState({forecast: forecast});
console.log("Forecast saved to state(inside function)");
console.log(this.state.forecast);
});
console.log("Forecast saved to state(outside function)");
console.log(this.state.forecast);
}
Console output:
Forecast saved to state(outside function)
[]
Returned forecast:
(5) [{…}, {…}, {…}, {…}, {…}]
Forecast saved to state(inside function)
(5) [{…}, {…}, {…}, {…}, {…}]