cartItems is a state array that contains the items that user adds and the logic that I have used is that if the item already exists in the cart then increase its quantity else put the quantity to 1.
const [cartItems,setCartItems]=useState([])
const handleAddItem=(item)=>{
if(!cartItems.find(product=>product.id===item.id)){
setCartItems([...cartItems,{...item,quantity:1}])
}
else{
setCartItems([...cartItems,
cartItems[cartItems.findIndex(product=>product.id===item.id)]
.quantity++])
}
}
After adding a item 5 times to the cart I'm getting following result but I only want object inside the array and not other elements.
[Object, 1, 2, 3, 4]
0: Object
id: 1
name: "Sunday"
price: 100
quantity: 5
1: 1
2: 2
3: 3
4: 4
Figured out the code below can be used in else condition
else{
cartItems[cartItems.findIndex(product=>product.id===item.id)].quantity++
setCartItems([...cartItems])
}