Chartjs-Chart.js charts not rendering data until I inspect element, is it because of async?

0👍

Your assumption is right, the problem is related to the asynchronus fetch() method.

There’s no need to create the charts in the window.onload. They should be created once the fetched data is available in a format to be used in the chart configuration. Therefore, the correct place to do this is at the end of the last fetch(...).then().

fetch('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv')
    .then(response => {
      return response.text();
    })
    .then((data) => {
      ...
      chartItCTCases(cases, days);
      chartItCTDeaths(deaths, days);
    })

Please have a look at your amended code below.

window.onload = function() {
  getData('New York');
}

function chartItCTCases(cases, days) {
  var ctx = document.getElementById('CoronaChartCTCases').getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: days,
      datasets: [{
        label: 'Cases',
        data: cases,
        backgroundColor: "rgb(207,181,59)"
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Total CoronaVirus Cases in the State'
      },
      maintainAspectRatio: false,
      responsive: true,
      scales: {
        xAxes: [{
          ticks: {
            autoSkip: true,
            maxTicksLimit: 12
          },
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Days since first case in the State'
          },
        }],
        yAxes: [{
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Total Cases in the state'
          }
        }]
      }
    }
  });
}

function chartItCTDeaths(deaths, days) {
  var ctx = document.getElementById('CoronaChartCTDeaths').getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: days,
      datasets: [{
        label: 'Deaths',
        data: deaths,
        backgroundColor: "rgb(207,181,59)"
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Total CoronaVirus Deaths in the State'
      },
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        xAxes: [{
          ticks: {
            autoSkip: true,
            maxTicksLimit: 12
          },
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Days since first case in the State'
          },
        }],
        yAxes: [{
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Total Deaths in the state'
          }
        }]
      }
    }
  });
}


function getData(state) {
  cases = [];
  deaths = [];
  days = [];
  fetch('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv')
    .then(response => {
      return response.text();
    })
    .then((data) => {
      const table = data.split('\n').slice(1);
      curDay = 0;
      table.forEach((row) => {
        const columns = row.split(',');
        if (columns[1] == state) {
          cases.push(columns[3]);
          deaths.push(columns[4]);
          days.push(curDay++);
        }
      });
      chartItCTCases(cases, days);
      chartItCTDeaths(deaths, days);
    })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div class="col-xs-12">
  <div style="height: 300px; width: 45%;display:inline-block;">
    <canvas id="CoronaChartCTCases"> </canvas>
  </div>
  <div style="height: 300px; width: 45%;display:inline-block;">
    <canvas id="CoronaChartCTDeaths"></canvas>
  </div>
</div>

Leave a comment