Basic Cart functionality

Add test-api function for contact page
This commit is contained in:
Michał Gdula 2024-04-30 14:48:32 +01:00
parent e2e68ab1fb
commit b7bc7da366
8 changed files with 142 additions and 24 deletions

43
front/src/lib/cart.ts Normal file
View file

@ -0,0 +1,43 @@
import { get, writable } from "svelte/store";
// Load content from localstorage
let local = [];
try {
local = JSON.parse(localStorage.getItem("basket")) || []
} catch {
console.error("Failed to load cart")
}
// Store function
function createCartStore() {
const cart = writable(local);
function addToCart(item: any) {
cart.update((cart) => [...cart, item]);
}
function getLength() {
return get(cart).length;
}
function removeByUUID(uuid: string) {
cart.update((cart) => cart.filter((item) => item.uuid !== uuid))
}
return {
...cart,
addToCart,
getLength,
removeByUUID,
}
}
// Create store
const Cart = createCartStore();
// Make sure to update localstorage on any changes
Cart.subscribe((value) => {
localStorage.setItem("basket", JSON.stringify(value));
});
export default Cart;