From 4ee5613a7899534db4ce6d6af799f784e80a7b5e Mon Sep 17 00:00:00 2001 From: kleap-admin Date: Sun, 18 Jan 2026 18:28:25 +0000 Subject: [PATCH] Update lib/use-cart.ts --- lib/use-cart.ts | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 lib/use-cart.ts diff --git a/lib/use-cart.ts b/lib/use-cart.ts new file mode 100644 index 0000000..f6ce78d --- /dev/null +++ b/lib/use-cart.ts @@ -0,0 +1,49 @@ +"use client"; +import { useState, useEffect } from "react"; +import { Product } from "@/lib/data"; + +type CartItem = Product & { quantity: number }; + +export function useCart() { + const [cart, setCart] = useState([]); + + useEffect(() => { + const savedCart = localStorage.getItem("cart"); + if (savedCart) setCart(JSON.parse(savedCart)); + }, []); + + const saveCart = (newCart: CartItem[]) => { + setCart(newCart); + localStorage.setItem("cart", JSON.stringify(newCart)); + }; + + const addToCart = (product: Product) => { + const existing = cart.find((item) => item.id === product.id); + if (existing) { + saveCart( + cart.map((item) => + item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item + ) + ); + } else { + saveCart([...cart, { ...product, quantity: 1 }]); + } + }; + + const removeFromCart = (id: string) => { + saveCart(cart.filter((item) => item.id !== id)); + }; + + const updateQuantity = (id: string, quantity: number) => { + if (quantity < 1) return removeFromCart(id); + saveCart( + cart.map((item) => (item.id === id ? { ...item, quantity } : item)) + ); + }; + + const clearCart = () => saveCart([]); + + const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0); + + return { cart, addToCart, removeFromCart, updateQuantity, clearCart, total }; +}