Add src/context/cartContext.tsx

This commit is contained in:
2026-06-09 22:45:22 +00:00
parent 1431d3c335
commit ddfa89a985

View File

@@ -0,0 +1,91 @@
import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react';
interface CartItem {
id: string;
name: string;
price: string; // Storing as string for display, will parse for calculations
quantity: number;
imageSrc: string;
imageAlt?: string;
variant?: string;
}
interface CartContextType {
cartItems: CartItem[];
addToCart: (item: Omit<CartItem, 'quantity'>) => void;
removeFromCart: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
getTotalPrice: () => string;
}
const CartContext = createContext<CartContextType | undefined>(undefined);
export const CartProvider = ({ children }: { children: ReactNode }) => {
const [cartItems, setCartItems] = useState<CartItem[]>(() => {
if (typeof window !== 'undefined') {
const savedCart = localStorage.getItem('cart');
return savedCart ? JSON.parse(savedCart) : [];
}
return [];
});
useEffect(() => {
if (typeof window !== 'undefined') {
localStorage.setItem('cart', JSON.stringify(cartItems));
}
}, [cartItems]);
const addToCart = (item: Omit<CartItem, 'quantity'>) => {
setCartItems((prevItems) => {
const existingItem = prevItems.find((cartItem) => cartItem.id === item.id);
if (existingItem) {
return prevItems.map((cartItem) =>
cartItem.id === item.id
? { ...cartItem, quantity: cartItem.quantity + 1 }
: cartItem
);
} else {
return [...prevItems, { ...item, quantity: 1 }];
}
});
};
const removeFromCart = (id: string) => {
setCartItems((prevItems) => prevItems.filter((item) => item.id !== id));
};
const updateQuantity = (id: string, quantity: number) => {
setCartItems((prevItems) => {
if (quantity <= 0) {
return prevItems.filter((item) => item.id !== id);
}
return prevItems.map((item) =>
item.id === id ? { ...item, quantity: quantity } : item
);
});
};
const getTotalPrice = () => {
const total = cartItems.reduce((sum, item) => {
const priceValue = parseFloat(item.price.replace(/[^0-9.-]+/g, ""));
return sum + priceValue * item.quantity;
}, 0);
return `$${total.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
return (
<CartContext.Provider
value={{ cartItems, addToCart, removeFromCart, updateQuantity, getTotalPrice }}
>
{children}
</CartContext.Provider>
);
};
export const useCart = () => {
const context = useContext(CartContext);
if (context === undefined) {
throw new Error('useCart must be used within a CartProvider');
}
return context;
};