Chartjs-Chart JS: Old chart data not clearing

0👍

This is because internally chart.js still populates the labels array so you will need to clear that one before replacing your data:

chart.data.labels = [];
chart.data.datasets[0].data = newData;
chart.update();
const options = {
  type: 'line',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
        x: 'hi',
        y: 5
      }, {
        x: 'test',
        y: 10
      }, {
        x: 'end',
        y: 2
      }],
      borderColor: 'pink'
    }]
  },
  options: {}
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);

chart.data.labels = [];
chart.data.datasets[0].data = [{
  x: 'k',
  y: 1
}, {
  x: 't',
  y: 4
}, {
  x: 'a',
  y: 5
}];
chart.update();
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>

Leave a comment