Files
salar-store/lib/cart.ts
T

40 lines
943 B
TypeScript

export type CartItem = {
productId: string;
variantId?: string;
slug: string;
name: string;
image: string;
price: number;
qty: number;
};
const KEY = "salar-cart";
export function getCart(): CartItem[] {
if (typeof window === "undefined") return [];
try {
const raw = window.localStorage.getItem(KEY);
return raw ? (JSON.parse(raw) as CartItem[]) : [];
} catch {
return [];
}
}
export function cartCount() {
return getCart().reduce((sum, item) => sum + item.qty, 0);
}
export function addToCart(item: CartItem) {
const cart = getCart();
const index = cart.findIndex(
(entry) => entry.productId === item.productId && entry.variantId === item.variantId,
);
if (index >= 0) {
cart[index] = { ...cart[index], qty: cart[index].qty + item.qty };
} else {
cart.push(item);
}
window.localStorage.setItem(KEY, JSON.stringify(cart));
window.dispatchEvent(new Event("cart-updated"));
}