chart.jschartjs-2.6.0

Chart JS Replace All Dataset Data


I want to replace my chart data entirely with a new array of objects. The chart data was replaced by new data but the chart is not updating after I called mychart.update(). Is there any way to replace the entire data without destroying the chart?

Here's my code:

  Livewire.on('changeData', () => {
    myChart.data.datasets.data = @this.data;
    myChart.update();

    console.log(myChart.data.datasets.data);
  })

Old Data

Old Data

New Data

New Data


Solution

  • This is because you are doing it wrong, the datasets field is an array containing all datasets so it doesn't contain a data field. You need to target the specific dataset from which you want to replace the data like so:

    myChart.data.datasets[datasetIndex].data = @this.data; // in case you only have 1 dataset you can just hardcode a 0
    myChart.update();