Chartjs-Updating chart.js with array index 0 doesn't work

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]))

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();
}

Leave a comment