Add product to cart from anywhere

Make a global function that adds a product to the current cart
This commit is contained in:
2021-11-08 13:00:31 +01:00
parent 571f5d0a6d
commit 378a64f2b0
3 changed files with 13 additions and 34 deletions

View File

@@ -1,7 +1,7 @@
<script lang="ts">
import { capitalizeFirstLetter } from '$utils/functions'
import { cartId, cartData } from '$utils/stores/shop'
import { addNotification } from '$utils/notifications'
import { addToCart } from '$utils/functions/shop'
import { capitalizeFirstLetter } from '$utils/functions'
// Components
import Button from '$components/atoms/Button.svelte'
import Image from '$components/atoms/Image.svelte'
@@ -55,33 +55,6 @@
ratio: 0.68,
},
]
/**
* Handling add to cart
*/
const addToCart = async () => {
const updatedCart = await fetch('/api/swell', {
method: 'POST',
body: JSON.stringify({
action: 'addToCart',
cartId: $cartId,
productId: product.product_id,
quantity: 1,
})
})
if (updatedCart.ok) {
const newCart = await updatedCart.json()
$cartData = newCart
// Show notification
addNotification({
title: 'Added to cart',
name: `${productShop.name} - x1`,
image: productShop.images[0].file.url,
})
}
}
</script>
<section class="poster-layout grid">
@@ -98,7 +71,7 @@
<Button
text="Add to cart"
color="pinklight"
on:click={addToCart}
on:click={() => addToCart($cartId, shopProduct)}
/>
</div>