| 14 | let index; |
| 15 | |
| 16 | const onAdd = (product, quantity) => { |
| 17 | const checkProductInCart = cartItems.find((item) => item._id === product._id); |
| 18 | |
| 19 | setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity); |
| 20 | setTotalQty((prevTotalQty) => prevTotalQty + quantity); |
| 21 | |
| 22 | if(checkProductInCart) { |
| 23 | const updatedCartItems = cartItems.map((cartProduct) => { |
| 24 | if(cartProduct._id === product._id) return { |
| 25 | ...cartProduct, |
| 26 | quantity: cartProduct.quantity + quantity |
| 27 | } |
| 28 | }) |
| 29 | |
| 30 | setCartItems(updatedCartItems); |
| 31 | } else { |
| 32 | product.quantity = quantity; |
| 33 | |
| 34 | setCartItems([...cartItems, { ...product }]); |
| 35 | } |
| 36 | |
| 37 | toast.success(`${qty} ${product.name} added to the cart.`); |
| 38 | } |
| 39 | |
| 40 | const onRemove = (product) => { |
| 41 | foundProduct = cartItems.find((item) => item._id === product._id); |