Reputation: 27
<html>
<body>
<canvas id="chart" style="width:400%;max-width:400px"></canvas>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js">
</script>
<script >
const xlabels= [];
chartit();
async function chartit(){
await getData();
const ctx = document.getElementById('chart').getContext('2d');
const xlabels = [];
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: xlabels,
datasets: [{
label: "Covid-19",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: xlabels
}]
},
});
};
async function getData(){
const response =await fetch('https://disease.sh/v3/covid-19/historical/Lebanon?
lastdays=30');
const data = await response.json();
const {timeline} = data;
xlabels.push(timeline.cases);
console.log(timeline.cases);
};
</script>
</body>
</html>
I can get the data in the console,but when I stored it into xlabels ,nothing appears on the graph ,I want to dispaly date on x-axis and number of cases on y-axis
It should look like this
Upvotes: 0
Views: 186
Reputation: 5937
you didn't pass the proper data to the chart object.
Example below:
let xlabels = [];
chartit();
async function chartit() {
await getData();
const ctx = document.getElementById("chart").getContext("2d");
const myChart = new Chart(ctx, {
type: "bar",
data: {
labels: xlabels.map(o => o.date),
datasets: [
{
label: "Covid-19",
fill: true,
lineTension: 0.1,
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: xlabels.map(o => o.cases),
},
],
},
});
}
async function getData() {
const response = await fetch(
"https://disease.sh/v3/covid-19/historical/Lebanon?lastdays=30"
);
const data = await response.json();
const { timeline } = data;
const cases = timeline.cases;
for (const item in cases) {
xlabels.push({ date: item, cases: cases[item] });
}
//console.log(timeline.cases);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<html>
<body>
<canvas id="chart" style="width: 400%; max-width: 400px"></canvas>
</body>
</html>
Upvotes: 1