Update lib/use-cart.ts

This commit is contained in:
kleap-admin 2026-01-18 18:28:25 +00:00
parent 8e4ac01183
commit 4ee5613a78
1 changed files with 49 additions and 0 deletions

49
lib/use-cart.ts Normal file
View File

@ -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<CartItem[]>([]);
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 };
}