Issue
I'm trying to loop through an object and add up the numbers in there.
const [cartCount, setCartCount] = useState(0)
for (let i = 1; i <= Object.keys(cartItems).length; i++) { //cartItems is the object
setCartCount(cartCount + cartItems[i])
}
but any attempt to update the state throws me the too many renders error. So how can I fix this?
Solution
You can simply initialize your state with your value.
const initialCount = Object.values(cartItems).reduce((acc, value) => acc + value, 0)
const [cartCount, setCartCount] = useState(initialCount)
But if you just need to have it stored once, you don't even need a state, you can keep your const
Answered By - dbuchet
Answer Checked By - - Clifford M. (ReactFix Volunteer)