Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Pinia add to cart #1297

Merged
merged 2 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions components/Products/ProductsSingleProduct.vue
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@

<script setup>
/**
* Vue.js component that displays a single product.
* Component that displays a single product.
*
* @component
* @example
Expand Down Expand Up @@ -119,7 +119,7 @@ watch(
* @return {Promise<void>} A Promise that resolves when the product has been successfully added to the cart.
*/
const addProductToCart = async (product) => {
cart.addToCart(product);
await cart.addToCart(product);

watchEffect(() => {
if (isLoading.value === false) {
Expand Down
25 changes: 18 additions & 7 deletions store/useCart.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const useCart = defineStore("cartState", {
);

if (foundProductInCartIndex > -1) {
this.cart[foundProductInCartIndex].quantity += newCartItem.quantity;
this.cart[foundProductInCartIndex].quantity += 1;
} else {
// We need to construct a cart item that matches the expected structure in `this.cart`
const productCopy = {
Expand All @@ -48,6 +48,7 @@ export const useCart = defineStore("cartState", {
price: newCartItem.total, // Assuming 'total' is the price for one item
slug: newCartItem.product.node.slug,
};

this.cart.push(productCopy);
}
} else {
Expand Down Expand Up @@ -80,12 +81,22 @@ export const useCart = defineStore("cartState", {
getCartTotal() {
const currencySymbol = useRuntimeConfig().public.currencySymbol || "kr";

return this.cart.reduce(
(total, product) =>
total +
Number(product.price.replace(currencySymbol, "")) * product.quantity,
0
);
const total = this.cart.reduce((total, product) => {
// Assuming product.price is a string that includes the currency symbol
const numericPrice = product.price
.replace(currencySymbol, "")
.replace(/[^0-9.]+/g, "");

// Convert the cleaned string to a floating-point number
const price = parseFloat(numericPrice);

const productTotal = price * product.quantity;

return total + productTotal;
}, 0);

// Format the total with the currency symbol and return it
return `${currencySymbol} ${total.toFixed(2)}`;
},
},
persist: true,
Expand Down