2

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

Jose Lora
  • 1,392
  • 4
  • 12
  • 18
vivek kn
  • 107
  • 1
  • 18
  • 45

5 Answers5

2

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, Migration to v4 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
    }
]
greybeard
  • 2,249
  • 8
  • 30
  • 66
slobert
  • 71
  • 4
  • Hi sobert, i got the same kinda issue may be you can help me. Kindly view the question at https://stackoverflow.com/questions/70618144/is-there-any-method-to-map-or-represent-api-data-to-chart-in-reactjs – Beren Jan 08 '22 at 07:20
0

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
  }]
};
Yousuf dev
  • 24
  • 1
0
import { useEffect, useState } from "react";
import "chart.js/auto";                                         /////
import { Line } from "react-chartjs-2";                         /////

const WeekMonthWeather = (props) => {
  const { latitude, longitude } = props;
  const [chartData, setChartData] = useState({ datasets: [] }); /////

  const fetchData = async () => {
    try {
      const response = await fetch(
        `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&hourly=temperature_2m`
      );
      const data = await response.json();
      if (data && data.hourly) {
        // check if data.hourly is defined
        console.log(data);
        const temperatures = data.hourly.temperature_2m;
        console.log(temperatures);
        const labels = data.hourly.time;
        console.log(labels);
        setChartData({
          labels: labels,
          datasets: [
            {
              label: "Temperature",
              data: temperatures,
              backgroundColor: "rgba(75,192,192,0.2)",
              borderColor: "rgba(75,192,192,1)",
              borderWidth: 1,
            },
          ],
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    fetchData();
  }, [latitude, longitude]);
 return (
    <div style={{ height: "512px", width: "1024px" }}>
      <h2>Weather Chart</h2>
      <Line data={chartData} />
    </div>
  );
};

export default WeekMonthWeather;

I am new in reactjs and this approach work for me.

  1. import "chart.js/auto";
  2. import { Line } from "react-chartjs-2";
  3. const [chartData, setChartData] = useState({ datasets: [] });
greybeard
  • 2,249
  • 8
  • 30
  • 66
-1
import {Chart as ChartJS} from 'chart.js/auto'

is essential, this fixed my problem

jozinho22
  • 459
  • 2
  • 7
  • 24
-1

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.

Jenny
  • 494
  • 1
  • 4
  • 16