expense-tracker-react icon indicating copy to clipboard operation
expense-tracker-react copied to clipboard

An error is thrown from Balance component when the Transactions length is 0

Open meghsohor opened this issue 4 years ago • 2 comments

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;

meghsohor avatar Apr 22 '20 04:04 meghsohor

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

vishnuprasad1992 avatar May 26 '21 06:05 vishnuprasad1992

reduce callback has 4 arguments:

  1. current value
  2. previous value
  3. current index
  4. 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);

dawnawaits avatar Sep 03 '21 09:09 dawnawaits