63 lines
1.5 KiB
TypeScript
63 lines
1.5 KiB
TypeScript
import { useState } from "react";
|
|
|
|
export interface CartItem {
|
|
id: string;
|
|
name: string;
|
|
price: number;
|
|
quantity: number;
|
|
}
|
|
|
|
export const useCheckout = () => {
|
|
const [cartItems, setCartItems] = useState<CartItem[]>([]);
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const addToCart = (item: CartItem) => {
|
|
setCartItems((prev) => {
|
|
const existing = prev.find((i) => i.id === item.id);
|
|
if (existing) {
|
|
return prev.map((i) => (i.id === item.id ? { ...i, quantity: i.quantity + item.quantity } : i));
|
|
}
|
|
return [...prev, item];
|
|
});
|
|
};
|
|
|
|
const removeFromCart = (id: string) => {
|
|
setCartItems((prev) => prev.filter((item) => item.id !== id));
|
|
};
|
|
|
|
const updateQuantity = (id: string, quantity: number) => {
|
|
setCartItems((prev) =>
|
|
prev.map((item) => (item.id === id ? { ...item, quantity: Math.max(1, quantity) } : item))
|
|
);
|
|
};
|
|
|
|
const getTotal = () => {
|
|
return cartItems.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2);
|
|
};
|
|
|
|
const checkout = async () => {
|
|
setIsLoading(true);
|
|
try {
|
|
// Simulate checkout process
|
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
setCartItems([]);
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Checkout failed");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
return {
|
|
cartItems,
|
|
isLoading,
|
|
error,
|
|
addToCart,
|
|
removeFromCart,
|
|
updateQuantity,
|
|
getTotal,
|
|
checkout
|
|
};
|
|
};
|