I have found many questions similar to the subject, however, I couldn’t understand the logic, as most of these are asked/explained in the PHP/ MySQL community.
I’m building an eCommerce store, where I need to handle cart items. The problem is already mentioned in the subject. Below is a short snippet of my code.
const [cartItems, setCartItems] = useState([]) // initial state of cartItems array
const handleCartUpdate = (id,title, price, qty) => {
// first checking if cart is empty or not
const cartLength = cartItems.legnth >=1 ? true : false
// Check if item exist with the id as given in parameters
if(cartLength) {
const checkItemExist = cartItems.find(item => item.id == id)
// Now, if item exist, update the propert 'qty' , My approach is as under:
if (checkItemExist) {
cartItems.map(product => {
if(product.id == id) {
return {product, qty: qty+1
}
}
return product
setCartItems(...cartItems, product)
}
} else {
setCartItems(...cartItems, {...})
}
}
After that, I am unable to understand how to update the cartItems