Reputation: 287
As stated in the title, how to set the data with a state value in react for highcharts? The value of this.state.number is 0 / undefined
CODE
getFirstMonthOpenEnhancements(){
fetch(`http://ca-fpscfb2:4000/1stMonthOpenedEnhancements?airline=${this.state.airlineName}&product=${this.state.airlineProduct}`)
.then(response => response.json())
.then( response =>
this.setState(
{
number: parseInt(response.data.total)
}
))
.catch(err => console.error(err))
}
componentDidMount(){
this.getFirstMonthOpenEnhancements();
let chart = this.refs.chart.getChart();
chart.series[4].setData([this.state.number, 4, 4, 4]);
}
Upvotes: 0
Views: 313
Reputation: 1442
The this.state.number
property is undefined because your API request is asynchronous, so when you are asking for the value of this.state.number
its undefined because your API call hasn't returned yet.
Theres a couple different solutions but in my opinion the most elegant is returning a promise.
getFirstMonthOpenEnhancements(){
return new Promise((resolve, reject) => {
fetch(`http://ca-fpscfb2:4000/1stMonthOpenedEnhancements?airline=${this.state.airlineName}&product=${this.state.airlineProduct}`)
.then(response => response.json())
.then( response =>
return resolve(parseInt(response.data.total))
))
.catch((err) => { return reject(err) });
});
}
componentDidMount(){
this.getFirstMonthOpenEnhancements()
.then((someNumber) => {
let chart = this.refs.chart.getChart();
chart.series[4].setData([someNumber, 4, 4, 4]);
this.setState({ number: someNumber });
})
.catch((err) => { console.log(err); });
}
Upvotes: 1