Home > Software design >  Error: Uncaught TypeError: Cannot read properties of undefined (reading 'map')
Error: Uncaught TypeError: Cannot read properties of undefined (reading 'map')

Time:08-12

What's the problem in the code? I can't seem to get it. The error shows:

utils.ts:53 Uncaught TypeError: Cannot read properties of undefined (reading 'map') and

react-dom.development.js:18687 The above error occurred in the <ForwardRef(ChartComponent)> component

I have attached the code. Whenever i run the code, the screen becomes blank and white. After removing the <Line../> snippet the app runs fine so the error seems to be in that particular section. But i can't seem to understand what's the error.

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { CryptoState } from '../CryptoContext';
import { HistoricalChart } from '../config/api';
import { createTheme } from '@material-ui/core/styles';
import { CircularProgress, makeStyles, ThemeProvider } from '@material-ui/core';
import { Line } from 'react-chartjs-2';



const useStyles = makeStyles((theme) => ({
  container:{
    width: "75%",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    marginTop: 25,
    padding: 40,
    [theme.breakpoints.down("md")]:{
      width: "100%",
      marginTop: 0,
      padding: 20,
      paddingTop: 0,
    },
  },
}));

const CoinInfo = ({ coin }) => {

  const [historicalData, setHistoricalData] = useState();
  const [days, setDays] = useState(1);

  const { currency } = CryptoState();

  const fetchHistoricalData = async () => {
    const { data } = await axios.get(HistoricalChart(coin.id,days,currency)) 

    setHistoricalData(data.prices);
  };

  useEffect(() => {
    fetchHistoricalData();
  }, [currency, days]);

  const darkTheme = createTheme({
    palette: {
      primary : {
        main: "#fff",
      },
      type: "dark",
    }
  });
  
  const classes = useStyles();

  //console.log("data",historicalData);

  return (
    <ThemeProvider theme={darkTheme}>
      <div className = {classes.container}>        
        {!historicalData ? (
          <CircularProgress
            style={{ color: "#40E0D0" }}
            size={250}
            thickness={1}
          />
        ): (
          <>
            <Line
              data={{
                labels: historicalData && historicalData.map((coin) => {
                  let date = new Date(coin[0]);
                  let time = 
                          date.getHours() > 12
                            ? `${date.getHours() - 12}:${date.getMinutes()} PM`
                            : `${date.getHours()}:${date.getMinutes()} AM`;
                  return days===1?time: date.toLocaleDateString();
                })
              }}
            />
          </>
        )}

      </div>
    </ThemeProvider>
  )
}

export default CoinInfo

Output of console.log("data", HistoricalData): Output

CodePudding user response:

I looked at the react-chartjs-2 source code, and there seems to be a bug in props of the root Chart component.

You need to add a datasets field to the object you pass as data prop. It should be an array, and later will be mapped by one of the library's inner functions. (probably that's where the error is coming from)

Like the documentation:

 const data = {
labels: labels,
datasets: [{
  label: 'My First dataset',
  backgroundColor: 'rgb(255, 99, 132)',
  borderColor: 'rgb(255, 99, 132)',
  data: [0, 10, 5, 2, 20, 30, 45],
}]
};

CodePudding user response:

Before return() simply add

import { Chart, registerables } from 'chart.js';
 Chart.register(...registerables);
  • Related