Chartjs-How do I destroy/update Chart Data in this chart.js code example?

1👍

Chart.js provides a helper class from which you can access all the chart instances on a page.

If you want to destroy all the instances before update/reload use the following code:

Chart.helpers.each(Chart.instances, function (instance) {
         instance.destroy();
    });

If you want to destroy a particular chart using the canvas id, use the following code:

Chart.helpers.each(Chart.instances, function (instance) {
        if (instance.chart.canvas.id === "yourChartId") {
            instance.destroy();
            return;
        }
    });

0👍

You can modify the data used by the chart directly.

From there documentation

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

Here you can pass the new data with the reference to the chart object. You can save the reference wwhen you create new Chart(...).

This is helpful to render the charts faster and in a smooth manner.

Leave a comment