Skip to content

Commit bb784ae

Browse files
committed
Fix Pinia add to cart
1 parent a7c30cb commit bb784ae

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

components/Products/ProductsSingleProduct.vue

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666

6767
<script setup>
6868
/**
69-
* Vue.js component that displays a single product.
69+
* Component that displays a single product.
7070
*
7171
* @component
7272
* @example
@@ -119,7 +119,7 @@ watch(
119119
* @return {Promise<void>} A Promise that resolves when the product has been successfully added to the cart.
120120
*/
121121
const addProductToCart = async (product) => {
122-
cart.addToCart(product);
122+
await cart.addToCart(product);
123123
124124
watchEffect(() => {
125125
if (isLoading.value === false) {

store/useCart.js

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,9 @@ export const useCart = defineStore("cartState", {
3939
);
4040

4141
if (foundProductInCartIndex > -1) {
42-
this.cart[foundProductInCartIndex].quantity += newCartItem.quantity;
42+
// We need to update the quantity
43+
44+
this.cart[foundProductInCartIndex].quantity += 1;
4345
} else {
4446
// We need to construct a cart item that matches the expected structure in `this.cart`
4547
const productCopy = {
@@ -48,6 +50,7 @@ export const useCart = defineStore("cartState", {
4850
price: newCartItem.total, // Assuming 'total' is the price for one item
4951
slug: newCartItem.product.node.slug,
5052
};
53+
5154
this.cart.push(productCopy);
5255
}
5356
} else {
@@ -80,12 +83,24 @@ export const useCart = defineStore("cartState", {
8083
getCartTotal() {
8184
const currencySymbol = useRuntimeConfig().public.currencySymbol || "kr";
8285

83-
return this.cart.reduce(
84-
(total, product) =>
85-
total +
86-
Number(product.price.replace(currencySymbol, "")) * product.quantity,
87-
0
88-
);
86+
//console.log("Cart:", this.cart);
87+
88+
const total = this.cart.reduce((total, product) => {
89+
// Assuming product.price is a string that includes the currency symbol
90+
const numericPrice = product.price
91+
.replace(currencySymbol, "")
92+
.replace(/[^0-9.]+/g, "");
93+
94+
// Convert the cleaned string to a floating-point number
95+
const price = parseFloat(numericPrice);
96+
97+
const productTotal = price * product.quantity;
98+
99+
return total + productTotal;
100+
}, 0);
101+
102+
// Format the total with the currency symbol and return it
103+
return `${currencySymbol} ${total.toFixed(2)}`;
89104
},
90105
},
91106
persist: true,

0 commit comments

Comments
 (0)