I know this has been asked before many times but I am curious to see what I’m doing wrong with this simple Chart.JS chart and adding data to it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Our First Line Chart</title>
</head>
<body>
<div style="width: 900px; height: 400px;">
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'line',
data: {
labels: ['12AM', '1AM', '2AM', '3AM', '4AM', '5AM'],
datasets: [{
label: 'Temperature',
data: [43, 46, 55, 65, 56, 44],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
function addData(chart, label, newData) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(newData);
});
chart.update();
};
addData(myChart, '6AM', 32);
</script>
</body>
</html>
It shows the chart just fine, but the chart does not update to add the new data that I’m trying to add with the addData function.