react-chart2: giving me Cannot read properties of undefined (reading 'map')

Viewed 3959

I am trying to use react-chartjs-2 in my project to create a chart and I am getting the following error:

TypeError: Cannot read properties of undefined (reading 'map')
setDatasets
C:/Users/vivek/code/src/utils.ts:46
  43 |   currentData: ChartData<TType, TData, TLabel>,
  44 |   nextDatasets: ChartDataset<TType, TData>[]
  45 | ) {
> 46 |   currentData.datasets = nextDatasets.map(nextDataset => {
  47 |     // given the new set, find it's current match
  48 |     const currentDataset = currentData.datasets.find(
  49 |       dataset =>

And, this is my code:

import React from "react";
import { Bar } from "react-chartjs-2";

const BarChart = () => {
  return (
    <div>
      <Bar
        data={{
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        }}
        width={600}
        height={400}
        options={{ maintainAspectRatio: false }}
      />
    </div>
  );
};
export default BarChart;

I am trying to create a bar chart

4 Answers

You have mistake in giving data. Check the documentation and follow the structure. Here is the example from documentation visit here

const labels = Utils.months({count: 7});
const data = {
  labels: labels,
  datasets: [{
    label: 'My First Dataset',
    data: [65, 59, 80, 81, 56, 55, 40],
    backgroundColor: [
      'rgba(255, 99, 132, 0.2)',
      'rgba(255, 159, 64, 0.2)',
      'rgba(255, 205, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(201, 203, 207, 0.2)'
    ],
    borderColor: [
      'rgb(255, 99, 132)',
      'rgb(255, 159, 64)',
      'rgb(255, 205, 86)',
      'rgb(75, 192, 192)',
      'rgb(54, 162, 235)',
      'rgb(153, 102, 255)',
      'rgb(201, 203, 207)'
    ],
    borderWidth: 1
  }]
};

Maybe this will be helpful for someone?

I ran into the exact same error above, my versions are as follows:

"chart.js": "^3.6.2", "react": "^17.0.2", "react-chartjs-2": "^4.0.0",

The key here is in fact the documentation, [https://react-chartjs-2.netlify.app/docs/migration-to-v4][1] specifically in my case it was the section "v4 — Line component" roughly halfway down the page.

Here is an example of the code that I got working after reviewing the above mentioned documentation, (and banging my head against a wall for hours!!).

import React, { useState, useEffect }  from "react";
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';
import { Chart as ChartJS, LineController, LineElement, PointElement, LinearScale, Title } from 'chart.js';

ChartJS.register(LineController, LineElement, PointElement, LinearScale, Title);


function Graph() {    
    useEffect(() => {
        const fetchSamplings = async () => {
            const res = await fetch("http://192.168.1.100:8080/consumer/v1/sampling/sensor/esp_planter_1/humidity/interval/24")
            const data = await res.json();
            
            setChartData({
                labels: data.map((sampling) => sampling.samplingDate),
                datasets: [{
                    label: "Humidity",
                    data: data.map((sampling) => sampling.humidity)                    
                }]
            });
        }
        fetchSamplings();        
    }, [])

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

    return(
        <div style={{height: "1024px", width: "2048px"}}>
            <Chart type='line' data={chartData} />
        </div>
    )
}

export default Graph;

note the returned json from the fetch looks like:

[
    {
        samplingDate: "2021-12-22T02:50:35.393+00:00",
        sensor: "esp_planter_1",
        humidity: 51.5
    },
    {
        samplingDate: "2021-12-22T02:49:34.874+00:00",
        sensor: "esp_planter_1",
        humidity: 53.2
    },
    {
        samplingDate: "2021-12-22T02:48:34.867+00:00",
        sensor: "esp_planter_1",
        humidity: 52.4
    }
]

Hope this helpful!!

  [1]: https://react-chartjs-2.netlify.app/docs/migration-to-v4
import {Chart as ChartJS} from 'chart.js/auto'

is essential, this fixed my problem

I had the same issue. My component looked liked this:

<Doughnut
  datasetIdKey='id'
  data={setChartData}
  options={options}
/>

After I changed

data={chartData}

that error was gone.

Related