Skip to content

Commit 0878ff0

Browse files
authored
Merge pull request #1287 from w3bdesign/dev
Dev
2 parents 13d5a9d + 49f0121 commit 0878ff0

File tree

3 files changed

+105
-94
lines changed

3 files changed

+105
-94
lines changed

components/Layout/LayoutCart.vue

Lines changed: 34 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -46,92 +46,69 @@
4646

4747
<script setup>
4848
import _ from "lodash";
49-
import { ref, watch } from "vue";
50-
49+
import {
50+
ref,
51+
onBeforeMount,
52+
onMounted,
53+
onBeforeUnmount,
54+
computed,
55+
watchEffect,
56+
} from "vue";
5157
import GET_CART_QUERY from "@/apollo/queries/GET_CART_QUERY.gql";
52-
53-
import { getCookie, formatPrice } from "@/utils/functions";
54-
58+
import { getCookie } from "@/utils/functions";
5559
import { useCart } from "@/store/useCart";
5660
57-
const cartLength = useState("cartLength", () => 0);
58-
const subTotal = useState("subTotal", "");
59-
const remoteError = useState("remoteError", () => false);
60-
61-
const cartChanged = ref(false);
62-
const loading = ref(true);
63-
64-
const cart = useCart();
65-
6661
const { data, error, pending, execute } = await useAsyncQuery(GET_CART_QUERY, {
6762
options: { fetchPolicy: "cache-and-network" },
6863
});
6964
70-
const updateCartDisplay = () => {
71-
if (!data?.value?.cart?.contents?.nodes?.length) {
72-
return;
73-
}
74-
75-
const remoteCartLength = data.value.cart.contents.nodes.reduce(
76-
(total, product) => total + product.quantity,
77-
0
78-
);
65+
const cart = useCart();
66+
const cartChanged = ref(false);
67+
const loading = ref(true);
7968
80-
const remoteTotal = data.value.cart.contents.nodes.reduce(
81-
(total, product) => {
82-
// Remove non-numeric characters and convert to number
83-
const productTotal = Number(product.total.replace(/[^0-9.-]+/g, ""));
84-
return total + productTotal;
85-
},
69+
const cartContents = computed(() => data.value?.cart?.contents?.nodes || []);
70+
const cartLength = computed(() =>
71+
cartContents.value.reduce((total, product) => total + product.quantity, 0)
72+
);
73+
const subTotal = computed(() =>
74+
cartContents.value.reduce(
75+
(total, product) => total + Number(product.total.replace(/[^0-9.-]+/g, "")),
8676
0
87-
);
88-
89-
cartLength.value = remoteCartLength;
90-
subTotal.value = remoteTotal;
91-
remoteError.value = error;
92-
93-
if (remoteCartLength !== cart.getCartQuantity) {
94-
cartChanged.value = true;
95-
}
96-
};
97-
98-
onBeforeMount(() => {
99-
execute();
100-
updateCartDisplay();
101-
});
102-
103-
onMounted(() => {
104-
loading.value = false;
105-
});
77+
)
78+
);
79+
const remoteError = ref(false);
10680
107-
// Debounce the execution of fetching data
10881
const debouncedExecute = _.debounce(() => {
10982
if (process.client && !pending.value && getCookie("woo-session")) {
11083
execute(); // Re-fetch the data
111-
updateCartDisplay();
11284
}
11385
}, 2000);
11486
115-
// Watch for changes in the cart state
116-
watch(
117-
() => cart.getCartQuantity,
118-
() => {
87+
watchEffect(() => {
88+
if (cart.getCartQuantity !== cartLength.value) {
11989
cartChanged.value = true;
120-
debouncedExecute();
12190
}
122-
);
91+
});
92+
93+
onBeforeMount(() => {
94+
execute();
95+
});
12396
12497
onMounted(() => {
98+
loading.value = false;
12599
const intervalId = setInterval(() => {
126100
if (cartChanged.value) {
127101
cartChanged.value = false;
128102
debouncedExecute();
129103
}
130104
}, 5000);
131105
132-
// Clear the interval when the component is unmounted to prevent memory leaks
133106
onBeforeUnmount(() => {
134107
clearInterval(intervalId);
135108
});
136109
});
110+
111+
watchEffect(() => {
112+
remoteError.value = error.value;
113+
});
137114
</script>

components/Products/ProductsSingleProduct.vue

Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
<div class="pt-1 mt-2">
5353
<CommonButton
5454
@common-button-click="addProductToCart(data.product)"
55-
:is-loading="isLoading"
55+
:is-loading="isTestLoading"
5656
>
5757
ADD TO CART</CommonButton
5858
>
@@ -87,10 +87,11 @@ import { stripHTML, filteredVariantName } from "@/utils/functions";
8787
8888
import { useCart } from "@/store/useCart";
8989
90-
const isLoading = useState("isLoading", () => false);
91-
9290
const cart = useCart();
9391
92+
// You can now access the loading state directly from the cart store
93+
const isTestLoading = computed(() => cart.loading);
94+
9495
const selectedVariation = ref(); // TODO Pass this value to addProductToCart()
9596
9697
const props = defineProps({
@@ -109,7 +110,7 @@ watch(
109110
dataValue.product?.variations?.nodes[0].databaseId;
110111
}
111112
},
112-
{ immediate: true },
113+
{ immediate: true }
113114
);
114115
115116
/**
@@ -119,31 +120,12 @@ watch(
119120
* @return {Promise<void>} A Promise that resolves when the product has been successfully added to the cart.
120121
*/
121122
const addProductToCart = async (product) => {
122-
const productId = product.databaseId ? product.databaseId : product;
123-
const productQueryInput = {
124-
productId,
125-
};
126-
127-
isLoading.value = true;
128-
129-
const addToCartvariables = { input: productQueryInput };
130-
131123
cart.addToCart(product);
132124
133-
const { mutate, onDone, onError } = useMutation(ADD_TO_CART_MUTATION, {
134-
addToCartvariables,
135-
});
136-
137-
mutate(addToCartvariables);
138-
139-
onDone(() => {
140-
isLoading.value = false;
141-
// Refresh the page
142-
window.location.reload();
143-
});
144-
145-
onError(() => {
146-
isLoading.value = false;
125+
watchEffect(() => {
126+
if (isTestLoading.value === false) {
127+
window.location.reload();
128+
}
147129
});
148130
};
149131
</script>

store/useCart.js

Lines changed: 62 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { defineStore } from "pinia";
22

3+
import ADD_TO_CART_MUTATION from "@/apollo/mutations/ADD_TO_CART_MUTATION.gql";
4+
35
/**
46
* Manages a shopping cart store using the Pinia library.
57
*
@@ -18,18 +20,52 @@ const state = {
1820
export const useCart = defineStore("cartState", {
1921
state: () => state,
2022
actions: {
21-
addToCart(product) {
22-
const foundProductInCartIndex = this.cart.findIndex(
23-
(cartProduct) => product.slug === cartProduct.slug
24-
);
23+
async addToCart(product) {
24+
this.loading = true;
25+
try {
26+
console.log("Adding to cart:", product);
27+
console.log("Adding product.databaseId to cart:", product.databaseId);
28+
29+
const { mutate } = useMutation(ADD_TO_CART_MUTATION);
30+
const response = await mutate({
31+
input: {
32+
productId: product.databaseId,
33+
quantity: 1, // Assuming you're adding one product at a time
34+
},
35+
});
36+
37+
if (response.data && response.data.addToCart) {
38+
console.log("Response from Add To Cart mutation:", response);
39+
this.loading = false;
40+
// Assuming the response returns the updated cart item, we need to handle it properly
41+
const newCartItem = response.data.addToCart.cartItem;
42+
const foundProductInCartIndex = this.cart.findIndex(
43+
(cartProduct) => newCartItem.product.node.slug === cartProduct.slug
44+
);
2545

26-
if (foundProductInCartIndex > -1) {
27-
this.cart[foundProductInCartIndex].quantity += 1;
28-
} else {
29-
const productCopy = { ...product, quantity: 1 };
30-
this.cart.push(productCopy);
46+
if (foundProductInCartIndex > -1) {
47+
this.cart[foundProductInCartIndex].quantity += newCartItem.quantity;
48+
} else {
49+
// We need to construct a cart item that matches the expected structure in `this.cart`
50+
const productCopy = {
51+
...newCartItem.product.node,
52+
quantity: newCartItem.quantity,
53+
price: newCartItem.total, // Assuming 'total' is the price for one item
54+
slug: newCartItem.product.node.slug,
55+
};
56+
this.cart.push(productCopy);
57+
}
58+
} else {
59+
// Handle the case where the mutation does not return the expected data
60+
this.error = "Did not receive expected cart data from the server.";
61+
}
62+
} catch (error) {
63+
this.error = error.message || "An error occurred while adding to cart.";
64+
} finally {
65+
this.loading = false;
3166
}
3267
},
68+
3369
removeProductFromCart(product) {
3470
this.cart.splice(this.cart.indexOf(product), 1);
3571
},
@@ -38,10 +74,26 @@ export const useCart = defineStore("cartState", {
3874
},
3975
},
4076
getters: {
77+
/*
78+
4179
getCartQuantity() {
4280
return this.cart.reduce((total, product) => total + product.quantity, 0);
4381
},
44-
getCartTotal() {
82+
*/
83+
84+
getCartQuantity() {
85+
86+
//console.log("Cart is:", this.cart);
87+
88+
89+
if (!this.cart) {
90+
console.error("Cart is undefined");
91+
return 0;
92+
}
93+
return this.cart.reduce((total, product) => total + product.quantity, 0);
94+
},
95+
96+
getCartTotal() {
4597
const currencySymbol = useRuntimeConfig().public.currencySymbol || "kr";
4698

4799
return this.cart.reduce(

0 commit comments

Comments
 (0)