Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js update function (chart,labels,data) will not update the chart

I cannot debug the following code. I would like to update chart data (not add on top; delete current data and add completely new dataset). (Not)Working example on codepen:

https://codepen.io/anon/pen/bvBxpr

var config = {
  type: 'line',
  data: {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
       label: "My First dataset",
       data: [65, 0, 80, 81, 56, 85, 40],
       fill: false
    }]
   }
 };

    var ctx = document.getElementById("myChart").getContext("2d");
    var myChart = new Chart(ctx, config);

    labelsNew = ["Why", "u", "no", "work", "???"];
    dataNew = [2, 4, 5, 6, 10];

    function updateData(chart, label, data) {
      removeData();
      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();
}

$('.button-container').on('click', 'button', updateData(myChart, labelsNew, dataNew));
like image 345
lovemyjob Avatar asked Jul 25 '26 08:07

lovemyjob


2 Answers

I figured it out. This works:

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

$("#btn").click(function() {
addData (myChart, labelsNew, dataNew);
});

instead of pushing the data (which adds on), data needs to be allocated by " = ".

like image 133
lovemyjob Avatar answered Jul 27 '26 21:07

lovemyjob


I see 2 problems:

  • in function updateData() missing chart argument to removeData(chart);
  • click handler for button, use simply: $("#btn").click(function() { updateData(myChart, labelsNew, dataNew) });
like image 41
beaver Avatar answered Jul 27 '26 22:07

beaver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!