0👍
Getting data from server by axios is an asynchronous function.You will never know exact time of when data will receive.
So what you should do is, create the chart after you received all data from the server.
componentDidMount() {
this.state.mainCtx = document.getElementById('myChart').getContext('2d');
getDataFromServer(this.state.defaultMonth);//There should be a default value for initial load
}
getDataFromServer(month) {
axios.get('http://localhost:8080/avgTempsMonth/'.concat(month))
.then(res => {
const tempsMonth = res.data;
this.setState({ tempsMonth });
const tempsMonthLabels = [];
//
..converting data to tempsMonthLabels
//
this.setState({ tempsMonthLabels });
this.setState({ isLoading: false });
//// Create Chart over here after you received all data
let mainChart = new Chart(this.state.mainCtx, {
type: 'line',
data: {
labels: this.state.tempsMonthLabels,
datasets: [{
label: "My First dataset",
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 35, 3],
}]
},
options: {
title: {
display: true,
text: 'Custom Chart Title'
}
}
});
this.setState({mainChart});
////
})
}
handleChange = event => {
this.state.currentMonth = event;
this.getMonthTempsFromServer(event);
this.state.mainChart.data.labels = this.state.tempsMonthLabels;
this.state.mainChart.update();
}
Source:stackexchange.com