Chartjs-How to address type errors when removing data with chart.js?

0👍

First you didn’t put the chart in a variable so you had no way of doing things with it. Second part, you didnt pass the function to the onclick but executed it and putted the result in the onClick.

The way it is described in the docs only works if you pass a chart variable to the function and dont do it with a button.

Also you are using a verry outdated version of chart.js with syntax for the latest. You either need to update your version or use the V2 docs

var data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
  datasets: [
    {
      label: "Dataset #1",
      backgroundColor: "rgba(255,99,132,0.2)",
      borderColor: "rgba(255,99,132,1)",
      borderWidth: 2,
      hoverBackgroundColor: "rgba(255,99,132,0.4)",
      hoverBorderColor: "rgba(255,99,132,1)",
      data: [65, 59, 20, 81, 56, 55, 40],
    },
  ],
};

var options = {
  maintainAspectRatio: false,
};

const chart = new Chart("chart", {
  type: "pie",
  options: options,
  data: data,
});

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

let btn = document.createElement("button");
btn.innerHTML = "Remove data";
btn.onclick = removeData;
document.body.appendChild(btn);
body {
  background: #1d1f20;
  padding: 16px;
}

canvas {
  border: 1px dotted red;
}

.chart-container {
  position: relative;
  margin: auto;
  height: 80vh;
  width: 80vw;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Chart.js tutorial</title>
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <div class="chart-container">
    <canvas id="chart"></canvas>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
</body>

</html>

Leave a comment