I'm trying to do a balance of incomes/expenses at my budget admin app and i keep getting this error at my balance component: TypeError: Cannot read properties of undefined (reading 'type').
I think the problem may be related with the state I bring from my reducer that comes duplicated, 2 times with an empty array [] and 2 times full. I tried a lot but couldn't fix it.. any idea what it could be??
This is my balance component code:
export default function Balance(){
const operations = useSelector((state) => state.operations);
console.log(operations);
//Shows 4 arrays, 2 empty and 2 full
const [total, setTotal] = React.useState([]);
const operationsListCopy = [...operations];
React.useEffect(() => {
let entryArray = operationsListCopy.filter((oneOperation) => oneOperation.type == 'INCOME');
let entryArrayTotal = entryArray?.reduce((amount, item) => item.amount amount, 0);
let exitArray = operationsListCopy.filter((oneOperation) => oneOperation.type == 'EXPENSE');
let exitArrayTotal = exitArray?.reduce((amount, item) => item.amount amount, 0);
let arrayTotal = entryArrayTotal - exitArrayTotal;
setTotal(arrayTotal);
}, [operations]);
CodePudding user response:
You should check for null or undefined value before accessing it. you could add condition here
let entryArray = operationsListCopy.filter((oneOperation) => oneOperation?.type == 'INCOME');
and here
let exitArray = operationsListCopy.filter((oneOperation) => oneOperation?.type == 'EXPENSE');