Answer the question
In order to leave comments, you need to log in
Why is 1 element of Stat empty?
Hello, I have the following code
const [item, setItem] = useState({
id: null, name: "", price: "", weight: ""
})
const [cart, setCart] = useState([])
const addToCart = (id, name, price, weight) => {
setItem({item, id:id, name:name, price:price, weight:weight})
setCart(cart => [...cart, item])
}
Answer the question
In order to leave comments, you need to log in
For setCart, you need to use useEffect with an item dependency, since adding to the cart is essentially a side effect of setting a new item, in this case
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question