I've been doing some React exercises and one of them is creating shopping cart. I came across such a solution which fragment kind of perplexed me:
const addToCart = (item) => {
const cartCopy = [...cart]
const itemInCart = cartCopy.find(i => item.name === i.name)
if (itemInCart) {
itemInCart.quantity += 1
setCart(cartCopy)
} else {
setCart(prevCart => [...prevCart, {...item, quantity: 1}])
}
}
The interesting fragment is this one:
if (itemInCart) {
itemInCart.quantity += 1
setCart(cartCopy)
}
We are updating the found item's quantity. But how is it possible that this exact item updates at the same time its quantity in cartCopy
? I thought that mapping over cartCopy object is necessary and using a solution presented in answer in this post: Increase the quantity of an object in an array Javascript ,React, RecoilJs
The one without mapping is more straightforward but I would like to understand what is going on under the hood.
I would be grateful for explanation. Thanks :)