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 (
@@ -24,7 +55,7 @@ function ShoppingCart () {

{item.name}

${item.price}

- +
) )}
@@ -34,9 +65,17 @@ function ShoppingCart () {

{item.name}

- + {item.quantity} - +

Subtotal: ${item.quantity * item.price}

@@ -44,7 +83,9 @@ function ShoppingCart () {
-

Total: $0.00

+

Total: + {cart.reduce((total, item) => total + item.quantity * item.price, 0).toFixed(2)} +

)