({children})
| 4 | const Context = createContext(); |
| 5 | |
| 6 | export const StateContext = ({children}) => { |
| 7 | const [showCart, setShowCart] = useState(false); |
| 8 | const [cartItems, setCartItems] = useState([]); |
| 9 | const [totalPrice, setTotalPrice] = useState(); |
| 10 | const [totalQty, setTotalQty] = useState(0); |
| 11 | const [qty, setQty] = useState(1); |
| 12 | |
| 13 | let foundProduct; |
| 14 | let index; |
| 15 | |
| 16 | const onAdd = (product, quantity) => { |
| 17 | // check if product already in the cart |
| 18 | const checkProductInCart = cartItems.find((item) => item._id === product._id); |
| 19 | |
| 20 | setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity); |
| 21 | setTotalQty((prevTotalQty) => prevTotalQty + quantity); |
| 22 | |
| 23 | // if product already in cart, then increase the qty of product instead of add the same product in cart |
| 24 | if(checkProductInCart) { |
| 25 | // update the actual item in the cart |
| 26 | const updatedCartItems = cartItems.map((cartProduct) => { |
| 27 | if(cartProduct._id === product._id) return { |
| 28 | ...cartProduct, |
| 29 | quantity: cartProduct.quantity + quantity |
| 30 | } |
| 31 | }) |
| 32 | |
| 33 | setCartItems(updatedCartItems); |
| 34 | } else { |
| 35 | // if when dont have the item in the cart |
| 36 | product.quantity = quantity; |
| 37 | setCartItems([...cartItems, {...product}]); |
| 38 | } |
| 39 | toast.success(`${qty} ${product.name} added to the cart`); |
| 40 | } |
| 41 | |
| 42 | const onRemove = (product) => { |
| 43 | foundProduct = cartItems.find((item) => item._id === product._id) |
| 44 | const AddNewCartItems = cartItems.filter(item => item._id !== product._id); |
| 45 | |
| 46 | setTotalPrice(prevTotalPrice => prevTotalPrice - foundProduct.price * foundProduct.quantity) |
| 47 | setTotalQty(prevTotalQty => prevTotalQty - foundProduct.quantity); |
| 48 | setCartItems(AddNewCartItems); |
| 49 | } |
| 50 | |
| 51 | const toggleCartItemQuantity = (id, value) => { |
| 52 | foundProduct = cartItems.find((item) => item._id === id) |
| 53 | index = cartItems.findIndex((product) => product._id === id) |
| 54 | const AddNewCartItems = cartItems.filter(item => item._id !== id); |
| 55 | |
| 56 | if(value === 'inc') { |
| 57 | let newCartItems = [...AddNewCartItems, {...foundProduct, quantity: foundProduct.quantity + 1}] |
| 58 | setCartItems(newCartItems); |
| 59 | setTotalPrice(prevTotalPrice => prevTotalPrice + foundProduct.price) |
| 60 | setTotalQty(prevTotalQty => prevTotalQty + 1) |
| 61 | } else if(value === 'dec') { |
| 62 | if(foundProduct.quantity > 1) { |
| 63 | let newCartItems = [...AddNewCartItems, {...foundProduct, quantity: foundProduct.quantity - 1}] |
nothing calls this directly
no outgoing calls
no test coverage detected