|
| 1 | +import { Heading } from '~/Heading' |
| 2 | +import { CartProvider, useCart } from './Cart' |
| 3 | +import classnames from 'classnames' |
| 4 | +import { DialogConfirm } from './Dialog' |
| 5 | +import { useState } from 'react' |
| 6 | + |
| 7 | +export function App() { |
| 8 | + return ( |
| 9 | + <CartProvider> |
| 10 | + <ProductDetails productId={1} /> |
| 11 | + </CartProvider> |
| 12 | + ) |
| 13 | +} |
| 14 | + |
| 15 | +/**************************************** |
| 16 | + Start Here: |
| 17 | +*****************************************/ |
| 18 | + |
| 19 | +type Props = { |
| 20 | + productId: number |
| 21 | +} |
| 22 | + |
| 23 | +function ProductDetails({ productId }: Props) { |
| 24 | + return ( |
| 25 | + <div className="space-y-3"> |
| 26 | + <Heading>iPhone Pro Max</Heading> |
| 27 | + <div>Price: 1,199.00</div> |
| 28 | + <AddToCartButton productId={productId} /> |
| 29 | + </div> |
| 30 | + ) |
| 31 | +} |
| 32 | + |
| 33 | +/**************************************** |
| 34 | + Specialization (Task Two) Here: |
| 35 | +*****************************************/ |
| 36 | + |
| 37 | +function AddToCartButton({ productId }: { productId: number }) { |
| 38 | + const { cart, addToCart, removeFromCart } = useCart() |
| 39 | + const [confirmOpen, setConfirmOpen] = useState(false) |
| 40 | + const inCart = cart.includes(productId) |
| 41 | + |
| 42 | + function onClick() { |
| 43 | + if (!inCart) { |
| 44 | + addToCart(productId) |
| 45 | + } else { |
| 46 | + setConfirmOpen(true) |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + function remove() { |
| 51 | + removeFromCart(productId) |
| 52 | + setConfirmOpen(false) |
| 53 | + } |
| 54 | + |
| 55 | + return ( |
| 56 | + <> |
| 57 | + <button className={classnames('button', { 'bg-red-600': inCart })} onClick={onClick}> |
| 58 | + {!inCart ? 'Add To Cart' : 'Remove From Cart'} |
| 59 | + </button> |
| 60 | + <DialogConfirm |
| 61 | + title="Remove from Cart" |
| 62 | + onConfirm={remove} |
| 63 | + onCancel={() => setConfirmOpen(false)} |
| 64 | + isOpen={confirmOpen} |
| 65 | + > |
| 66 | + Are you sure you want to remove this item from the cart? |
| 67 | + </DialogConfirm> |
| 68 | + </> |
| 69 | + ) |
| 70 | +} |
0 commit comments