0
<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-axisenter image description here

It should look like this

enter image description here

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.