Chartjs-Why is the data from my API not displaying on my chart.js chart in React?

1👍

Your dataObject in axios res is not correct, you forgot intensity.
your Chart3.js have to look like:

import axios from "axios";
import React, {useState, useEffect} from "react";
import { Line } from "react-chartjs-2";
const Chart3 = () => {
  const [chartData, setChartData] = useState({});
  const [Forecast, setForecast] = useState([]);
  const [Actual, setActual] = useState([]);

  const chart = () => {
    let Fore = [];
    let Act = [];


    axios
      .get('https://api.carbonintensity.org.uk/intensity/2020-08-25T15: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));
        }
        setChartData({
          labels: Fore,
          datasets: [
            {
              label: "Forestreet",
              data: Act,
              backgroundColor: ["rgba(75, 192, 192, 0.6)"],
              borderWidth: 4
            }
          ]
        });
      })
      .catch(err => {
        console.log(err);
      });
    console.log(Fore, Act);
  };

  useEffect(() => {
    chart();
  }, []);
  return (
    <div className="App">
      <h1>Dankmemes</h1>
      <div style={{height:"500px", width:"500px"}}>
        <Line
          data={chartData}
          options={{
            responsive: true,
            title: { text: "ForeStreet", display: true },
            scales: {
              yAxes: [
                {
                  ticks: {
                    autoSkip: true,
                    maxTicksLimit: 10,
                    beginAtZero: true
                  },
                  gridLines: {
                    display: false
                  }
                }
              ],
              xAxes: [
                {
                  gridLines: {
                    display: false
                  }
                }
              ]
            }
          }}
        />
      </div>
    </div>
  );
};

export default Chart3;

the only difference is dataObject :
dataObj.intensity.forecast instead of dataObj.forecast
sandBox

Leave a comment