I am trying to get values of objects in an Array that I set to be added together, This function that I'm running will only be called onClick, but on the first click I am getting an error that says,
"react-dom.development.js:4309 Uncaught TypeError: Reduce of empty array with no initial value"
on the second click, it will work, but it will add two elements to the DOM(with the first one being added on the initial click). I've tried running this function inside of a useEffect, but it puts me into an infinite loop.
Code:
const [householdIncome, setHouseHoldIncome] = useState([]);
const [total, setTotal] = useState([]);
const name = useRef()
const income = useRef();
const clickValue = () => {
//get the value
let uName = name.current.value;
let uIncome = income.current.value;
// object that stores the values
let userIncome = {
id: Math.random() * 10,
name: uName,
Income: (+ uIncome)
}
setHouseHoldIncome((prevState) => (
[...prevState, userIncome]
))
const result = householdIncome.map((item)=>(item.Income)).reduce(function(a,b){return a+b});
//initial click will cause error when logging
console.log(result);
}