expense-tracker-react
expense-tracker-react copied to clipboard
An error is thrown from Balance component when the Transactions length is 0
The following line in Balance component:
const balance = amounts.reduce((acc, amount) => acc + amount).toFixed(2);
throws this error if the transactions list is empty:
TypeError: Reduce of empty array with no initial value
I have updated the line with this:
const balance = amounts.length > 0 ? amounts.reduce((acc, amount) => acc + amount).toFixed(2) : 0;
Same error occurs for same reason for the following lines in IncomeExpenses component:
const income = amounts.filter(amount => amount > 0).reduce((acc, amount) => acc + amount).toFixed(2);
const expense = (amounts.filter(amount => amount < 0).reduce((acc, amount) => acc + amount) * -1).toFixed(2);
I have updated those lines with these:
const income = amounts.length > 0 && amounts.filter(amount => amount > 0).length > 0 ? amounts.filter(amount => amount > 0).reduce((acc, amount) => acc + amount).toFixed(2) : 0.00;
const expense = amounts.length > 0 && amounts.filter(amount => amount < 0).length > 0 ? (amounts.filter(amount => amount < 0).reduce((acc, amount) => acc + amount) * -1).toFixed(2) : 0.00;
I also have the same error, can someone help with this?
I made onClick (delete function) in transaction.js as lambda function. that error was cleared. I will help you. Thanks, Brad
reduce callback has 4 arguments:
- current value
- previous value
- current index
- array we called reduce on
Specify the previous value as 0 and it should work fine.
const balance = amounts.reduce((acc, cur) => acc += cur,0).toFixed(2);