Reputation: 107
I want to read a .json file and use its data for the data attribute of a chart.js diagram.
My code is as follows:
const test = []
fetch("./load.json")
.then(response => {
return response.json();
})
.then(data => {
// console.log(data)
for (i = 0; i < data.length; i++) {
// console.log(data[i])
test.push(data[i])
}
});
console.log(test)
// setup block
const data = {
datasets: [{
label: 'Sales',
data: test,
borderColor: 'rgba(234,124,234,0.4)',
backgroundColor: 'rgba(34,14,24,0.4)'
}]
};
// config block
const config = {
type: 'line',
data,
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'second'
}
},
y: {
beginAtZero: true
},
xAxes: [{
type: "time",
time: {
min: 1628373600,
max: 1628460000
}
}]
}
}
};
// render / init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
My .json file:
[{"x": "2021-08-08T13:12:23", "y":3},
{"x": "2021-08-08T13:12:45", "y":5},
{"x": "2021-08-08T13:12:46", "y":6},
{"x": "2021-08-08T13:13:11", "y":3},
{"x": "2021-08-08T13:14:23", "y":9},
{"x": "2021-08-08T13:16:45", "y":1}]
I have tried to parse the data from the .json file and in console it shows up but I think the data attribute of chart.js is not able to read the data in the test variable.
Does somebody know how to do this?
Upvotes: 1
Views: 533
Reputation: 31321
Seems like the chart is being made before the data is ready since loading the json is an async proces, you can either instantiate the chart in your second .then
when the data is available or create the chart as you do and then in the second .then
update the data in the chart and call the update
method
Upvotes: 1