Reputation: 71
Thanks for any tips and or help! I've hit a wall here trying to get a chart to render. I've reverted to testing a very simple approach (code below) and I am still getting the following error:
TypeError: Cannot read properties of undefined (reading 'map')
I can log the data being set from the useEffect call, but I cant understand why its not making it into the Line graph. From the debugger (on utils.ts) I can see that (currentData = {labels: undefined, datasets: Array(0)}) and nextDatasets = undefined. I'm starting to wonder if there is some version mismatch somewhere, anyways thanks for any ideas!
import React, { useState, useEffect } from "react";
import {Line} from "react-chartjs-2";
function Graph() {
const myLabels = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
const [data, setData] = useState({});
useEffect(() => {
setData({
labels: myLabels,
datasets: [
{
label: 'The Level',
data: [21, 53, 65, 12, 32]
},
]
});
}, [])
console.log(data.datasets);
return(
<div style={{height: "500px", width: "500px"}}>
<Line data={data} />
</div>
)}
export default Graph;
The following version are in use: "react": "^17.0.2" with "chart.js": "^3.6.2", "react-chartjs-2": "^4.0.0"
Upvotes: 3
Views: 3825
Reputation: 71
After some reading... I re-visited my approach and came up with the following, I'm not sure this is the proper way to go about things, still learning so if anyone has any helpful comments they'd be welcomed!
I'm not sure I completely understand at this point, but I think that the main problem I had was related to the useEffect()
being used to build the data for the graph, as opposed to maybe effect the graph once it's there.
import React from "react";
import { useState } from "react";
import 'chart.js/auto';
import { Chart } from 'react-chartjs-2';
function Graph() {
const [chartData, setChartData] = useData();
return(
<div style={{height: "500px", width: "500px"}}>
<Chart type='line' data={chartData} />
</div>
)
}
export default Graph;
const useData = ( data = {} ) => {
const [state, setState] = useState(data);
data = {
labels: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
datasets: [
{
label: 'The Level',
data: [21, 53, 65, 12, 32]
},
]
}
return [data]
}
Upvotes: 2
Reputation: 191
By default data is blank, that's why it gives an error so just you have to ensure that if data is available then you can draw the line chart.
Just change one line of code: {data.datasets ? <Line data={data} /> : ""}
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
function Graph() {
const myLabels = ["monday", "tuesday", "wednesday", "thursday", "friday"];
const [data, setData] = useState({});
useEffect(() => {
setData({
labels: myLabels,
datasets: [
{
label: "The Level",
data: [21, 53, 65, 12, 32]
}
]
});
}, []);
console.log(data.datasets);
return (
<div style={{ height: "500px", width: "500px" }}>
{data.datasets ? <Line data={data} /> : ""}
</div>
);
}
export default Graph;
Upvotes: 1