-1

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);
        }
Leander
  • 36
  • 3
  • You can't use the updated state value in the same render cycle. Either use a `useEffect` dependent on `householdIncome` or do the manipulation on a seperate variable before setting. – pilchard May 24 '22 at 21:08
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – pilchard May 24 '22 at 21:09

0 Answers0