0

I have an array of chart data objects. I update the chart data by passing the index of the array and pulling data out of the object. This works perfectly for all indexes except 0.

When initializing the chart, I load the 0 index and the chart works perfectly as well, so I know it's not a data structure issue with that particular index. I don't get any errors when calling the update function on the chart with the 0 index.

Here's a codepen showing it not working with index 0.

Why is it not updating the chart for the 0 index?

Barrett Kuethen
  • 1,864
  • 7
  • 25
  • 33

2 Answers2

0

the update is not working. you should rerender the chart

 function resetChart() {
   const ctx = document.getElementById("myChart").getContext("2d");
   window.myChart = new Chart(ctx, chartData[curIndex]);
 }

 window.onload = function() {
  this.resetChart();
 };

function UpdateChart(index) {
  curIndex = index;
  myChart.data.labels = chartData[curIndex].data.labels;
  myChart.data.datasets[0].data = chartData[curIndex].data.datasets[0].data;
  myChart.data.datasets[0].label = chartData[curIndex].data.datasets[0].label;
  myChart.data.datasets[1].data = chartData[curIndex].data.datasets[1].data;
  myChart.data.datasets[1].label = chartData[curIndex].data.datasets[1].label;
  this.resetChart();
}
Garine
  • 574
  • 5
  • 21
0

Change:

window.myChart = new Chart(ctx, chartData[curIndex]);

to

window.myChart = new Chart(ctx, JSON.parse(JSON.stringify(chartData[curIndex])));

The reason being you need to clone the object otherwise myChart is the same as chartData[0] and when you click on 1 or 2, it overwrites 0.

This part of the code clones the object JSON.parse(JSON.stringify(chartData[curIndex]))

John
  • 3,716
  • 2
  • 19
  • 21