|
| 1 | +import { useState } from 'react'; |
| 2 | + |
| 3 | +const initialProducts = [{ |
| 4 | + id: 0, |
| 5 | + name: 'Baklava', |
| 6 | + count: 1, |
| 7 | +}, { |
| 8 | + id: 1, |
| 9 | + name: 'Cheese', |
| 10 | + count: 5, |
| 11 | +}, { |
| 12 | + id: 2, |
| 13 | + name: 'Spaghetti', |
| 14 | + count: 2, |
| 15 | +}]; |
| 16 | + |
| 17 | +const ShoppingCart = () => { |
| 18 | + const [products, setProducts] = useState(initialProducts) |
| 19 | + |
| 20 | + |
| 21 | + // Update an item in the shopping cart |
| 22 | + function handleIncreaseClick(productId) { |
| 23 | + setProducts(products.map((item) =>{ |
| 24 | + if(item.id===productId){ |
| 25 | + return {...item,count:item.count+1} |
| 26 | + }else{ |
| 27 | + return item |
| 28 | + } |
| 29 | + })) |
| 30 | + |
| 31 | + // OR We can do it like below as well . |
| 32 | + |
| 33 | + // const data = products.map((item) => { |
| 34 | + // if (item.id === productId) { |
| 35 | + // return { ...item, count: item.count + 1 } |
| 36 | + // } else { |
| 37 | + // return item |
| 38 | + // } |
| 39 | + // }) |
| 40 | + // setProducts(data) |
| 41 | + |
| 42 | + } |
| 43 | + |
| 44 | + // |
| 45 | + const handleDecreaseClick =(ProductId)=>{ |
| 46 | + const data=products.map((item)=>{ |
| 47 | + if(item.id===ProductId){ |
| 48 | + return {...item,count:item.count-1} |
| 49 | + }else{ |
| 50 | + return item |
| 51 | + } |
| 52 | + }) |
| 53 | + // if your count is 0 then that item should be removed, uncomment below and check. |
| 54 | + |
| 55 | + // const result=data.filter((item)=> item.count>0) |
| 56 | + // setProducts(result) |
| 57 | + setProducts(data) |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + // setProducts(products.map((item) =>{ |
| 62 | + // if(item.id===productId){ |
| 63 | + // return {...item,count:item.count+1} |
| 64 | + // }else{ |
| 65 | + // return item |
| 66 | + // } |
| 67 | + |
| 68 | + // })) |
| 69 | + } |
| 70 | + |
| 71 | + return ( |
| 72 | + <ul> |
| 73 | + {products.map(product => ( |
| 74 | + <li key={product.id}> |
| 75 | + {product.name} |
| 76 | + {' '} |
| 77 | + (<b>{product.count}</b>) |
| 78 | + <button onClick={() => { |
| 79 | + handleIncreaseClick(product.id); |
| 80 | + }}> |
| 81 | + + |
| 82 | + </button> |
| 83 | + <button onClick={() => { |
| 84 | + handleDecreaseClick(product.id); |
| 85 | + }}> |
| 86 | + - |
| 87 | + </button> |
| 88 | + </li> |
| 89 | + ))} |
| 90 | + </ul> |
| 91 | + ); |
| 92 | +} |
| 93 | +export default ShoppingCart; |
0 commit comments