Files
housesof/src/utils/functions/shop.ts
Félix Péault 378a64f2b0 Add product to cart from anywhere
Make a global function that adds a product to the current cart
2021-11-08 13:00:31 +01:00

34 lines
949 B
TypeScript

import { addNotification } from '$utils/functions/notifications'
import { cartData } from '$utils/stores/shop'
/**
* Add a product to a cart
*/
export const addToCart = async (cartId: string, product: any, quantity: number = 1) => {
if (cartId && cartId !== 'null') {
const updatedCart = await fetch('/api/swell', {
method: 'POST',
body: JSON.stringify({
action: 'addToCart',
cartId,
productId: product.id,
quantity,
})
})
if (updatedCart.ok) {
const newCart = await updatedCart.json()
cartData.set(newCart)
// Show notification
addNotification({
title: 'Added to cart',
name: `${product.name} - x1`,
image: product.images[0].file.url,
})
}
} else {
console.log('No active cart')
}
}