Home > OS >  Uncaught TypeError: Cannot read properties of null (reading 'labels')
Uncaught TypeError: Cannot read properties of null (reading 'labels')

Time:07-23

I'm trying to build a LineChart using chartjs, but I'm running through some errors which I can't tell the source of, the data is transfered as wanted from the server and (according to the dates and coinValue) splitted just fine. any idea what is the problem?

here are the errors:

errors

and here is my code:

import { Link } from "react-router-dom";
import { Line } from "react-chartjs-2";
import {Chart as chartjs, Title, Tooltip, LineElement, Legend, CategoryScale, LinearScale, PointElement} from "chart.js";

chartjs.register(
  Title, Tooltip, LineElement, Legend, CategoryScale, LinearScale, PointElement
)

function BitCoin() {
  const [data, setData] = React.useState(null);
  const [dates, setDates] = React.useState(null);
  const [coinValue, setCoinValue] = React.useState(null);
  const [chartData, setChartData] = useState(null);


  React.useEffect(() => {
    fetch("http://localhost:3001/bitcoin")
      .then((res) => res.json())
      .then((data) => {
        const twoDimensionArr = data.message;
        setData(twoDimensionArr);
        setDates(twoDimensionArr.map(item => item[0]));
        setCoinValue(twoDimensionArr.map(item => item[1]));
        setChartData({
          labels: twoDimensionArr.map(item => item[0]),
          datasets: [{
            label: "value of BTC in ILS",
            data: twoDimensionArr.map(item => item[1]),
            backgroundColor: 'gold'
          }]
        })
      })
  }, []);

  return (
    <div style={{textAlign:"center", fontFamily:"Comic Sans MC", fontSize:"100"}}>
      THIS IS THE BitCoin PAGE

      <nav>
        <Link to="/"> Home </Link>
      </nav>

      <nav>
        <Link to="/coins"> Coins </Link>
      </nav>

      <Line
      data = {chartData}
      />

    </div>
  )
}

export default BitCoin;

CodePudding user response:

This is because you pass null to the Line component.

You either need to init the data with empty state or conditionally render the Line.

Initial state:

const [chartData, setChartData] = useState({
    labels: [],
    datasets: [{
        data: []
    }]
});

Conditionally render:

{chartData !== null && <Line data={chartData}/>}

CodePudding user response:

Not familiar with that chart library, but my guess is that it's erroring out before your async data is returned from the API call. I would try creating valid uninitialized data to feed to the Line component on the initial render, or simply prevent the chart from loading until the data is returned. You can check if that's your issue with something like:

{chartData && <Line
      data = {chartData}
      />
}
  • Related