From 35961093ee86c9aa475188e29f240d606b1a5b87 Mon Sep 17 00:00:00 2001 From: stp Date: Wed, 28 Feb 2024 15:56:38 +0100 Subject: [PATCH 1/2] Steven Tong Phung not complete --- src/App.jsx | 66 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index d28c0b3..2dde89e 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,37 +1,75 @@ import './styles/reset.css' import './styles/index.css' -import initialStoreItems from './store-items' - -/* - Here's what a store item should look like - { - id: '001-beetroot', - name: 'beetroot', - price: 0.35 - } +import { useState } from 'react' - What should a cart item look like? 🤔 - */ -console.log(initialStoreItems) +import initialStoreItems from './store-items' export default function App() { // Setup state here... + const [store, setStore] = useState(initialStoreItems) + const [cart, setCart] = useState([]) + + const handleClick = (target) => { + const itemInCart = cart.findIndex((cartItem) => cartItem.id === target.id) + + if (itemInCart === -1){ + setCart([...cart,{...target, count: 1}]) + } + else{ + const newCart = [...cart] + newCart[itemInCart].count++ + setCart(newCart) + } + + } + + const incrementCartItem = (target) => { + const itemInCart = cart.findIndex((cartItem) => cartItem.id === target.id) + + const newCart = [...cart] + newCart[itemInCart].count++ + setCart(newCart) + } + + + return ( <>

Greengrocers

Your Cart

    - {/* Write some code here... */} + {cart.map((item, index) => ( +
  • + {item.name} +

    {item.name}

    + + {item.count} + + +
  • + ))}
From 8ecec828ad5a06d94644c7be645fddea40a5437c Mon Sep 17 00:00:00 2001 From: stp Date: Thu, 29 Feb 2024 08:26:22 +0100 Subject: [PATCH 2/2] decrement button in cart working --- src/App.jsx | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/App.jsx b/src/App.jsx index 2dde89e..5edcfca 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -14,7 +14,6 @@ export default function App() { const handleClick = (target) => { const itemInCart = cart.findIndex((cartItem) => cartItem.id === target.id) - if (itemInCart === -1){ setCart([...cart,{...target, count: 1}]) } @@ -34,6 +33,22 @@ export default function App() { setCart(newCart) } + const decrementCartItem = (target) => { + const itemInCart = cart.findIndex((cartItem) => cartItem.id === target.id) + // console.log(cart[itemInCart]) + + if (cart[itemInCart].count === 1) { + const updatedCart = cart.filter((cartItem, index) => index !== itemInCart); + console.log(updatedCart) + setCart(updatedCart); + + } else { + const newCart = [...cart] + newCart[itemInCart].count-- + setCart(newCart) + } + } + return ( @@ -64,7 +79,7 @@ export default function App() { src={`/assets/icons/${item.id}.svg`} alt={item.name} />

{item.name}

- + {item.count}