diff --git a/src/app/cartContext.tsx b/src/app/cartContext.tsx new file mode 100644 index 0000000..39b67af --- /dev/null +++ b/src/app/cartContext.tsx @@ -0,0 +1,87 @@ +"use client"; + +import React, { createContext, useContext, useState, useEffect } from "react"; + +interface CartItem { + id: string; + name: string; + price: number; + imageSrc: string; + quantity: number; +} + +interface CartContextType { + cartItems: CartItem[]; + addToCart: (product: { id: string; name: string; price: string; imageSrc: string; imageAlt?: string }) => void; + removeFromCart: (id: string) => void; + updateQuantity: (id: string, quantity: number) => void; + clearCart: () => void; + totalPrice: number; +} + +const CartContext = createContext(undefined); + +export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { + const [cartItems, setCartItems] = useState([]); + + useEffect(() => { + // Load cart from localStorage on mount + if (typeof window !== "undefined") { + const storedCart = localStorage.getItem("shopwel_cart"); + if (storedCart) { + setCartItems(JSON.parse(storedCart)); + } + } + }, []); + + useEffect(() => { + // Save cart to localStorage whenever it changes + if (typeof window !== "undefined") { + localStorage.setItem("shopwel_cart", JSON.stringify(cartItems)); + } + }, [cartItems]); + + const addToCart = (product: { id: string; name: string; price: string; imageSrc: string; imageAlt?: string }) => { + setCartItems((prevItems) => { + const itemExists = prevItems.find((item) => item.id === product.id); + if (itemExists) { + return prevItems.map((item) => + item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item + ); + } else { + const priceValue = parseFloat(product.price.replace("₹", "").replace("/kg", "").replace("/L", "")); + return [...prevItems, { ...product, price: priceValue, quantity: 1 }]; + } + }); + }; + + const removeFromCart = (id: string) => { + setCartItems((prevItems) => prevItems.filter((item) => item.id !== id)); + }; + + const updateQuantity = (id: string, quantity: number) => { + setCartItems((prevItems) => + prevItems.map((item) => (item.id === id ? { ...item, quantity: Math.max(1, quantity) } : item)) + ); + }; + + const clearCart = () => { + setCartItems([]); + }; + + const totalPrice = cartItems.reduce((total, item) => total + item.price * item.quantity, 0); + + return ( + + {children} + + ); +}; + +export const useCart = () => { + const context = useContext(CartContext); + if (context === undefined) { + throw new Error("useCart must be used within a CartProvider"); + } + return context; +};