39161-vm/frontend/src/CartContext.tsx
Flatlogic Bot 3a45bf3328 version7
2026-03-13 01:51:32 +00:00

35 lines
837 B
TypeScript

import React, { createContext, useContext, useState } from 'react';
interface CartItem {
id: number;
name: string;
price: number;
}
interface CartContextType {
cart: CartItem[];
addToCart: (product: CartItem) => void;
}
const CartContext = createContext<CartContextType | undefined>(undefined);
export const CartProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [cart, setCart] = useState<CartItem[]>([]);
const addToCart = (product: CartItem) => {
setCart((prev) => [...prev, product]);
};
return (
<CartContext.Provider value={{ cart, addToCart }}>
{children}
</CartContext.Provider>
);
};
export const useCart = () => {
const context = useContext(CartContext);
if (!context) throw new Error('useCart must be used within CartProvider');
return context;
};