Диаграммы js не отображают данные, пока я не проверю элемент, это из-за asyn c? - PullRequest
0 голосов
/ 14 апреля 2020

Я читаю данные из файла .csv и вводю данные в график chart.js для визуализации. Пожалуйста, взгляните на мой код. Он рендерится только тогда, когда я проверяю элемент после нажатия кнопки «Показать состояние» на кнопке. Кроме того, могу ли я изменить свою функцию getdata, чтобы обновить данные для графиков и повторно обработать их?

JavaScript ниже:

window.onload = function () {
    chartItCountryCases();
    chartItCountryDeaths();
    getData(state);

}


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'
                      }
                            } ]
                        }
            }
        });

        myChart.render();
    }

    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'
                      }
                            } ]
                        }
            }
        });

        myChart.render();
    }


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);
    }

HTML ниже:

<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> 

1 Ответ

0 голосов
/ 15 апреля 2020

Ваше предположение верно, проблема связана с асинхронным fetch() методом.

Нет необходимости создавать диаграммы в window.onload. Они должны быть созданы после того, как извлеченные данные станут доступны в формате, который будет использоваться в конфигурации диаграммы. Поэтому правильное место для этого - в конце последнего 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);
    })

. Пожалуйста, ознакомьтесь с исправленным кодом ниже.

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>
...