I'm using chart.js to make a simple chart. No problem producing the chart, but now I've added a remove data function per the documentation but I'm getting a type error. I assume it's because I'm incorrectly accessing the data
The error is as follows, and I'll link a JS fiddle file so you can see everything without me dumping in a wall of text.
"main.js:49 Uncaught TypeError: Cannot read properties of undefined (reading 'labels')"
My understanding is that this error tends to pop up due to scope issues, but I've defined the data globally so the function should be able to access it. I also thought that I was maybe accessing it wrong since it has a few nested arrays, so I tried btn.onclick = removeData(chart[0]); to access the first item in the chart object (the data variable) but that produced a similar error as above, but swapped in 'data' for 'labels'. Thanks for any help/input!
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>