Creating a straightforward bar chart using Chartjs 3.x
The process involves fetching JSON data from the server, parsing it, and storing specific parts in arrays. See the code snippet below:
serverData = JSON.parse(http.responseText);
console.log(serverData);
stundenProjekt = serverData.abzurechnen.nachProjekt.map((s) => {
return s.second.summe;
});
labelsP = serverData.abzurechnen.nachProjekt.map((p) => {
return p.first;
});
The goal is to utilize these arrays in the data and label fields of the chart. While stundenProjekt
as data
functions properly, using labelsP
as label
does not work. Refer to the chart code below:
const data = {
labels: labelsP,
datasets: [{
label: 'Projects',
data: stundenProjekt,
backgroundColor: ['#f4f40b'],
borderColor: ['#B1B101'],
borderWidth: 3,
}]
};
if (barChartProjekt) {
data.datasets.forEach((ds, i) => {
barChartProjekt.data.datasets[i].data = ds.data;
barChartProjekt.labels = newLabelsArray;
})
barChartProjekt.update();
} else {
barChartProjekt = new Chart(chart, {
type: 'bar',
data: data,
options: {
responsive: true,
plugins: {
legend: {
labels: {
color: "white",
font: {
size: 18
}
}
}
},
scales: {
y: {
ticks: {
color: "white",
font: {size: 18},
stepSize: 1,
beginAtZero: true
}
},
x: {
ticks: {
color: "white",
font: {
size: 14
},
stepSize: 1,
beginAtZero: true
}
}
}
}
});
}
To ensure the chart displays correctly, I resorted to manually entering the contents of labelsP
into the label
field, essentially bypassing the original approach. The contents and workaround are detailed below:
["nexnet-SB-Cloud", "AUTEC - PSK-System²", "Fritzsche", ...]
const data = {
labels: ["nexnet-SB-Cloud", "AUTEC - PSK-System²", "Fritzsche", ...],
datasets: [{
label: 'Projects',
data: stundenProjekt,
backgroundColor: ['#f4f40b'],
borderColor: ['#B1B101'],
borderWidth: 3,
}]
};
The functionality desired is for labelsP
to dynamically update with fresh data every few seconds. The mystery remains why supplying labelsP
alone in the label
field fails, while manually inputting its content makes the chart work flawlessly.