[Chartjs]-API data not loading in chart.js until element is inspected or page is resized

2👍

Since fetch makes an asynchronous call, you need to create your chart once the response is received. Therefore, simply place the chart creation code inside .then and it will work as shown below.

window.onload = function() {
  let dates = [];
  let confirmedCases = [];
  let confirmedRecovered = [];
  let confirmedDeaths = [];

  function addArrayFunc(date, confirmed, recovered, deaths) {
    dates.push(date);
    confirmedCases.push(confirmed);
    confirmedRecovered.push(recovered);
    confirmedDeaths.push(deaths);
  }

  fetch("https://pomber.github.io/covid19/timeseries.json")
    .then(response => response.json())
    .then(cases => {
      cases["Australia"].forEach(({
          date,
          confirmed,
          recovered,
          deaths
        }) =>
        addArrayFunc(date, confirmed, recovered, deaths)
      )
      new Chart(document.getElementById('myChart'), {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
              label: 'Confirmed',
              borderColor: 'pink',
              backgroundColor: 'pink',
              fill: 'false',
              data: confirmedCases
            },
            {
              label: 'Recovered',
              borderColor: 'blue',
              backgroundColor: 'blue',
              fill: 'false',
              data: confirmedRecovered
            },
            {
              label: 'Deaths',
              borderColor: 'green',
              backgroundColor: 'green',
              fill: 'false',
              data: confirmedDeaths
            }
          ]
        },
        options: {
          responsive: true,
          title: {
            display: true,
            text: 'Covid-19 Cases in Australia'
          },
        }
      });
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment