89 lines
2.4 KiB
TypeScript
89 lines
2.4 KiB
TypeScript
'use client';
|
|
|
|
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
|
|
|
export interface Product {
|
|
id: string;
|
|
title: string;
|
|
image: string;
|
|
l: string;
|
|
d: string;
|
|
brand: string;
|
|
price?: string | null;
|
|
badge?: string;
|
|
stock: boolean;
|
|
}
|
|
|
|
export interface CartItem extends Product {
|
|
quantity: number;
|
|
}
|
|
|
|
interface CartContextType {
|
|
cart: CartItem[];
|
|
addToCart: (product: Product) => void;
|
|
removeFromCart: (id: string) => void;
|
|
decreaseQuantity: (id: string) => void;
|
|
clearCart: () => void;
|
|
}
|
|
|
|
const CartContext = createContext<CartContextType | undefined>(undefined);
|
|
|
|
export function CartProvider({ children }: { children: ReactNode }) {
|
|
const [cart, setCart] = useState<CartItem[]>([]);
|
|
|
|
useEffect(() => {
|
|
const savedCart = localStorage.getItem('cart');
|
|
if (savedCart) {
|
|
setCart(JSON.parse(savedCart));
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
localStorage.setItem('cart', JSON.stringify(cart));
|
|
}, [cart]);
|
|
|
|
const addToCart = (product: Product) => {
|
|
setCart((prevCart) => {
|
|
const existingItem = prevCart.find((item) => item.id === product.id);
|
|
if (existingItem) {
|
|
return prevCart.map((item) =>
|
|
item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
|
|
);
|
|
}
|
|
return [...prevCart, { ...product, quantity: 1 }];
|
|
});
|
|
};
|
|
|
|
const decreaseQuantity = (id: string) => {
|
|
setCart((prevCart) => {
|
|
const existingItem = prevCart.find((item) => item.id === id);
|
|
if (existingItem?.quantity === 1) {
|
|
return prevCart.filter((item) => item.id !== id);
|
|
}
|
|
return prevCart.map((item) =>
|
|
item.id === id ? { ...item, quantity: item.quantity - 1 } : item
|
|
);
|
|
});
|
|
};
|
|
|
|
const removeFromCart = (id: string) => {
|
|
setCart((prevCart) => prevCart.filter((item) => item.id !== id));
|
|
};
|
|
|
|
const clearCart = () => setCart([]);
|
|
|
|
return (
|
|
<CartContext.Provider value={{ cart, addToCart, removeFromCart, decreaseQuantity, clearCart }}>
|
|
{children}
|
|
</CartContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useCart() {
|
|
const context = useContext(CartContext);
|
|
if (!context) {
|
|
throw new Error('useCart must be used within a CartProvider');
|
|
}
|
|
return context;
|
|
}
|