I'm trying to add a canvasjs chart component into another component called dashboard. Sometimes, the data is getting loaded and working fine, sometimes the data is not getting loaded and an error is thrown.
The error goes like this and it points to the doughnutchart.js page and not to dashboard.js page: TypeError: Cannot read property '0' of undefined
In the mentioned line
name: this.props.data.labels[0],
DoughnutChart.js :
import React, { Component } from "react";
import CanvasJSReact from "../../../assets/canvasjs.react";
var CanvasJSChart = CanvasJSReact.CanvasJSChart;
class DoughnutChart extends Component {
constructor(props) {
super(props);
console.log(this.props.data);
window.alert(JSON.stringify(this.props.data));
this.state = {
options: {},
};
}
componentWillReceiveProps(nextProps) {
console.log("componentWillReceiveProps", nextProps);
//console.log(this.props.data);
// if (this.props !== nextProps) {
// this.setState(nextProps);
// }
//console.log(nextProps.data.labels[0]);
console.log(this.props.data);
let options = {
animationEnabled: true,
theme: "light2",
// title: {
// text: "Customer Satisfaction",
// },
subtitles: [
{
// text: "71% Positive",
// verticalAlign: "center",
fontSize: 24,
dockInsidePlotArea: true,
},
],
data: [
{
type: "doughnut",
radius: "90%",
innerRadius: "50%",
showInLegend: true,
indexLabel: "{y}%",
//yValueFormatString: "#,###'%'",
toolTipContent: "{name}: <strong>{y}%</strong>",
indexLabelPlacement: "outside",
dataPoints: [
{
name: this.props.data.labels[0],
y: this.props.data.datasets[0].data[0],
},
{
name: this.props.data.labels[1],
y: this.props.data.datasets[0].data[1],
},
{
name: this.props.data.labels[2],
y: this.props.data.datasets[0].data[2],
},
],
},
],
};
this.setState({
options,
});
}
render() {
//let options = {};
return (
<div>
<CanvasJSChart
options={this.state.options}
/* onRef={ref => this.chart = ref} */
/>
{/*You can get reference to the chart instance as shown above using onRef. This allows you to access all chart properties and methods*/}
</div>
);
}
}
export default DoughnutChart;
Referred several links, couldn't overcome the issue.