i have a problem with a function, the second time it is executed the console return the error 'Uncaught ReferenceError: Cannot access 'total' before initialization'. The sum of the values seams ok, but i cant find why the function is giving this error.`
sumExpenses = () => {
const { expenses } = this.props;
const total = expenses.reduce((acc, e) => {
const parc = (Number(e.value) * Number(e.exchangeRates[e.currency].ask)).toFixed(2);
const final = Number(parc) Number(acc);
console.log(final);
return total;
}, 0);
};
The error:
Uncaught ReferenceError: Cannot access 'total' before initialization
at WalletForm.js:31:1
at Array.reduce (<anonymous>)
at WalletForm.sumExpenses (WalletForm.js:27:1)
at WalletForm.handleClick (WalletForm.js:18:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
`
Im trying to apply a table of exchange prices to as expenses app through redux. The values looks right on the state, but the navigator give me an error when i add the second expense.
CodePudding user response:
you are logging final
but returning total
.
sumExpenses = () => {
const { expenses } = this.props;
const total = expenses.reduce((acc, e) => {
const parc = (Number(e.value) * Number(e.exchangeRates[e.currency].ask)).toFixed(2);
const final = Number(parc) Number(acc);
console.log(final);
return final ;
}, 0);
};