Chartjs-Created an onclick function to remove data from a line chart in ChartsJs, but getting "Cannot read property 'data' of undefined" error

0👍

The problem is that your removeData() function expects a chart object but you don’t provide it in button onClick.

You can change your code as follows and it will work.

const chart = new Chart(document.getElementById("line-chart"), {
  type: 'line',
  data: {
    labels: [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050],
    datasets: [{ 
        data: [86,114,106,106,107,111,133,221,783,2478],
        label: "Jonnies Pizza",
        borderColor: "#3e95cd",
        fill: false
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Pizza Sales Worldwide'
    }
  }
});      

function removeData() {
    chart.data.labels.pop();
    chart.data.datasets[0].data.pop();
    chart.update();
}

Please have a look at your amended JSFiddle.

Leave a comment