sv_webshop/src/lib/stores/cartStore.ts
2025-01-13 14:31:37 +01:00

48 lines
1.2 KiB
TypeScript

import { writable } from 'svelte/store';
// Define the type for a product
export interface Product {
id: number;
title: string;
description: string;
imageUrl: string;
price: number;
quantity: number;
}
// Initialize the cart store
export const cart = writable<Product[]>([]);
// Add a product to the cart
export const addToCart = (product: Product) => {
cart.update((items) => {
const existingItem = items.find((item) => item.id === product.id);
if (existingItem) {
// If the product already exists, increase the quantity
return items.map((item) =>
item.id === product.id ? { ...item, quantity: item.quantity + 1 } : item
);
} else {
// If the product doesn't exist, add it to the cart
return [...items, { ...product, quantity: 1 }];
}
});
};
// Remove a product from the cart
export const removeFromCart = (productId: number) => {
cart.update((items) => items.filter((item) => item.id !== productId));
};
// Update the quantity of a product in the cart
export const updateQuantity = (productId: number, quantity: number) => {
cart.update((items) =>
items.map((item) => (item.id === productId ? { ...item, quantity } : item))
);
};
// Clear the cart
export const clearCart = () => {
cart.set([]);
};