I am new to using MongoDB and REACT, and I wanted to make a pie chart which could show the category name as well as the assigned total value of that category. This is an image of what the database looks like
I am using recharts as the library to help me create the pie chart. I have tried doing it using dummy data from a class but I have not been able to get it to work using data from the database. This is what I tried to do.
Any help is greatly appreciated, thank you.
class wallet {
constructor(name, balance, category) {
this.name = name;
this.balance = balance;
this.category = category;
}
}
const wallets = [
new wallet("Abdallah's wallet", 10000, "Work"),
new wallet("Uber eats", 1000, "Food"),
new wallet("University", 80000, "Work"),
new wallet("Bills", 10000, "House"),
];
function App() {
const dataPie = [];
for (let wallet in wallets) {
dataPie.push({
name: wallets[wallet].category,
value: wallets[wallet].balance,
});
}
console.log(dataPie);
return (
<div className="App">
<div>
<h1>Balance of Each Category</h1>
<PieChart width={400} height={400} test="hey, world!">
<Pie
dataKey="value"
isAnimationActive={true}
data={dataPie}
cx="50%"
cy="50%"
outerRadius={80}
fill="#8884d8"
label
/>
<Tooltip />
</PieChart>
</div>
</div>
);
}
Explanation
Are there any errors being produced? Just by purely looking at your code, my best guess is that the issue lies in your for loop where you are trying to push the wallet data into the dataPie array.
What you are trying to do (I assume) is to do perform a for...of loop similar to the one here. In this case, the syntax for your for loop should be changed where in is replaced with of. Next, since wallet is already referencing the iterable object itself, you no longer need to access value by index wallets[wallet], since wallet is also not an index.
You may have been confused and tried to use the for...in loop here which is used to iterate through properties in an object. However, in your implementation, you are trying to iterate through an array on objects instead.
Your Code:
for (let wallet in wallets) {
dataPie.push({
name: wallets[wallet].category,
value: wallets[wallet].balance,
});
}
My Fix:
for (let wallet of wallets) {
dataPie.push({
name: wallet.category,
value: wallet.balance,
});
}