Search code examples
javascriptjsonchart.jschartjs-2.6.0

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


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?


Solution

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