简体   繁体   English

反应:如何在 API 数据加载到我的 chart.js 图表时显示加载微调器

[英]React: How to get loading spinner to show whilst API data loads into my chart.js chart

I want a loading spinner to appear on the screen whilst API data loads and then the chart to appear and the spinner to disappear once it's all loaded.我希望加载微调器出现在屏幕上,同时加载 API 数据,然后显示图表,一旦全部加载,微调器就会消失。

I have managed to get the spinner to appear but the chart does not ever load - I am accessing the API and there are no errors, I know my code is wrong whether it's the order, etc.. but I cannot work out how to get it all to fit together.我已经设法让微调器出现,但图表永远不会加载 - 我正在访问 API 并且没有错误,我知道我的代码是错误的,无论是订单等等。但我不知道如何获取这一切都适合在一起。

code is below代码如下

import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import * as ReactBootStrap from 'react-bootstrap';
import axios from "axios";
import './Chart.css';

const Chart3 = () => {
    //Setting states for later use
  const [chartData, setChartData] = useState({});
  const [chartItem, setChartItem] = useState(null);
  const [loading, setLoading] = useState(false);

  const Chart = async () => {
      //Setting up variables to store data
    let Fore = [];
    let Act = [];
    try{
      const data = await axios
        .get('https://api.carbonintensity.org.uk/intensity/2020-09-01T15:30Z/2020-09-10T17:00Z')
        .then(res => {
          console.log(res);
          for (const dataObj of res.data.data) {
            Fore.push(parseInt(dataObj.intensity.forecast));
            Act.push(parseInt(dataObj.intensity.actual));
            setChartItem(res.data.data);
          }
          //Now setting chart data now we have the data from API and parsed it 
          setLoading(true)
          setChartData({
            labels: Fore,
            datasets: [
              {
                label: "Carbon Intensity Levels",
                data: Act,
                backgroundColor: "#F58A07",
                borderWidth: 4
              }
            ]
          });
      })
    } catch (e) {
      console.log(e)
    }

    useEffect(() => {
    Chart();
    }, []);
  }




//Chart is rendered below - data is accessed from chartData and the settings of the chart is configured under options
  return (
    <div className="App">
      <h1></h1>
      <div className="chart">
        {loading ? 
        <Line
          data={chartData}
          options={{
            responsive: true,
            title: { text: "2020-09-01T15:30Z - 2020-09-10T17:00Z", display: true },
            scales: {
              yAxes: [
                {
                  ticks: {
                    autoSkip: true,
                    maxTicksLimit: 100,
                    beginAtZero: true
                  },
                  gridLines: {
                    display: false
                  },
                  scaleLabel: {
                      display: true,
                      labelString: "Actual"
                  }
                }
              ],
              xAxes: [
                {
                  gridLines: {
                    display: false
                  },
                  scaleLabel: {
                      display: true,
                      labelString: "Forecast"
                  }

                }
              ]
            }
          }} /> : <ReactBootStrap.Spinner animation="border"/> }
      </div>
    </div>
  );
};

export default Chart3;

You have to use the NOT operator on the loading variable within the ternary operator to get the chart to display when data is fetched.您必须在三元运算符中的加载变量上使用 NOT 运算符才能在获取数据时显示图表。

...
{!loading ? 
            <Line
              data={chartData}
              options={{
                responsive: true,
                title: { text: "2020-09-01T15:30Z - 2020-09-10T17:00Z", display: true },
                scales: {
                  yAxes: [
                    {
                      ticks: {
                        autoSkip: true,
                        maxTicksLimit: 100,
                        beginAtZero: true
                      },
                      gridLines: {
                        display: false
                      },
                      scaleLabel: {
                          display: true,
                          labelString: "Actual"
                      }
                    }
                  ],
                  xAxes: [
                    {
                      gridLines: {
                        display: false
                      },
                      scaleLabel: {
                          display: true,
                          labelString: "Forecast"
                      }
    
                    }
                  ]
                }
              }} /> : <ReactBootStrap.Spinner animation="border"/> }
...

References:参考:

React.做出反应。 AJAX and APIs. AJAX 和 API。 https://reactjs.org/docs/faq-ajax.html . https://reactjs.org/docs/faq-ajax.html (Accessed December 2020) (2020 年 12 月访问)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM