diff --git a/src/11-shopping-cart/ShoppingCart.js b/src/11-shopping-cart/ShoppingCart.js index b731e81..fee7947 100644 --- a/src/11-shopping-cart/ShoppingCart.js +++ b/src/11-shopping-cart/ShoppingCart.js @@ -12,7 +12,38 @@ const items = [{ }] function ShoppingCart () { - const cart = [{ name: 'apple', quantity: 3, price: 0.39 }] + const [cart, setCart] = useState([]) + + function addToCart(item) { + const itemIndex = cart.findIndex((cartItem) => cartItem.name === item.name); + if (itemIndex !== -1) { + const updatedCart = [...cart]; + updatedCart[itemIndex].quantity++; + setCart(updatedCart); + } else { + setCart([ + ...cart, + { + name: item.name, + quantity: 1, + price: item.price, + }, + ]); + } + } + + function removeFromCart(item) { + const itemIndex = cart.findIndex((cartItem) => cartItem.name === item.name); + if (itemIndex !== -1) { + const updatedCart = [...cart]; + if (updatedCart[itemIndex].quantity > 1) { + updatedCart[itemIndex].quantity--; + } else { + updatedCart.splice(itemIndex, 1); + } + setCart(updatedCart); + } + } return (
${item.price}
- +- + {item.quantity} - +
Subtotal: ${item.quantity * item.price}