[Chartjs]-Chart.js update function (chart,labels,data) will not update the chart

7๐Ÿ‘

โœ…

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 โ€ = โ€œ.

1๐Ÿ‘

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

1๐Ÿ‘

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 addData(chart, label, data) {
    chart.data.labels = label
    chart.data.datasets.forEach((dataset) => {
        dataset.data = data;
    });
    chart.update();
}

function clickupdate(){
  addData(myChart, labelsNew, dataNew);
}
.chart-container {
  height: 300px;
  width: 500px;
  position: relative;
}

canvas {
  position: absolute;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<div class="button-container">
  <button onclick="clickupdate()">Change Data</button>
</div>
<div class="chart-container">
  <canvas id="myChart"></canvas>
</div>

Leave a comment