I'm developing a React app and trying to get Chartjs to work having imported it from its npm package. The following is the initialization code:
//in my constructor
this.usageChart = null;
//in componentDidMount
let chartContext = document.getElementById("proc_usage");
let initialDataIdle = [100, 100, 100, 100, 100, 100, 100, 100, 100, 100];
let initialDataOther = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
console.log("Creating chart");
this.usageChart = new Chart(chartContext, {
type: "line",
data: {
datasets: [
{ label: "User", fill: true, data: initialDataOther, backgroundColor: "rgba(244, 143, 177, 0.8)" },
{ label: "System", fill: true, data: initialDataOther, backgroundColor: "rgba(255, 235, 59, 0.8)" },
{ label: "IRQ", fill: true, data: initialDataOther, backgroundColor: "rgba(100, 181, 246, 0.8)" },
{ label: "Idle", fill: true, data: initialDataIdle, backgroundColor: "rgba(150, 150, 150, 0.4)" }
]
},
options: {
scales: {
xAxes: [{ stacked: true }],
yAxes: [{ stacked: true }]
},
plugins: {
stacked100: { enable: true }
}
}
});
console.log("Chart created: " + this.usageChart.data);
The problem is when I try to update the chart, this.usageChart.data
is undefined. In fact, in that last console.log()
call during initialization, it is also undefined. I cannot see what I am doing wrong. I am loading a plugin which allows a Line chart to be drawn as stacked with area between lines representing percentage. I don't know if perhaps this plugin is the issue, but I am getting no errors about it and the code was more or less taken verbatim from the plugin's example code.
Here is the code where I update the chart:
//from componentDidUpdate
usages['User'] = userUsage;
usages['System'] = sysUsage;
usages['IRQ'] = irqUsage;
usages['Idle'] = idleUsage;
console.log("updating chart");
this.usageChart.data.datasets.forEach((dataset) => {
dataset.data.shift();
dataset.data.push(usages[dataset.label]);
});
this.usageChart.update();
console.log("chart updated");
I did create a fiddle (I just copied your code into custom component) for you and there is no error in my case.
I think that there is error around here, as your chart is not being updated properly:
this.usageChart.data.datasets.forEach((dataset) => {
dataset.data.shift();
dataset.data.push(usages[dataset.label]);
});
Corrected version:
You were wrongly updating the data sets:
this.usageChart.data.datasets.forEach((dataset) => {
dataset.data.shift();
dataset.data = usages[dataset.label];
});
Please check the working fiddle and compare it with your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With