I was trying to create a chart using Chartjs in react. For that I used axios post method to get data from database from server that I created in Nodejs. When I used chartjs in axios I am getting this error "Uncaught TypeError: Cannot read properties of undefined (reading 'map')"
Here is my code:
const [userData, setData] = React.useState([]);
React.useEffect(()=> {
axios.post("http://localhost:3001/graph",
{
username:str
}).then(response=>{
Uname = response.data.username;
exp = response.data.expense;
inc = response.data.income;
console.log(inc);
console.log(exp);
data.push(exp);
data.push(inc);
});
setData({
labels: title,
datasets:[
{
label: "Expense",
data: data,
backgroundColor: ["red"]
}
]
});
console.log(userData);
})
I am getting empty array in userData. I tried most of the method online but nothing seems to work. Please if anyone can help me here its really imp.
Thank you.
Its because at first the userData is an empty array and after a while data goes to it and you can use it; one think that you can do is to use an if before defining map like this: {userData && userData.map ...}