Skip to content

1371 look into cart not updating after add to cart #1372

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

Merged
merged 7 commits into from
Sep 12, 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
79 changes: 36 additions & 43 deletions components/Cart/CartContents.vue
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
<template>
<template v-if="data.cart?.contents?.nodes?.length">
<div v-if="isLoading">
<h2 class="mt-64 text-3xl text-center">Loading cart...</h2>
</div>
<div v-else-if="error">
<h2 class="mt-64 text-3xl text-center text-red-500">Error loading cart. Please try again.</h2>
</div>
<div v-else-if="cartItems.length">
<h1 class="h-10 p-6 text-3xl font-bold text-center">Cart</h1>
<section class="mt-10">
<CartItem
v-for="product in data.cart.contents.nodes"
:key="product.id"
v-for="product in cartItems"
:key="product.key"
:product="product"
@remove="handleRemoveProduct"
/>
</section>
<CommonButton link-to="/checkout" v-if="showCheckoutButton" center-button>
<CommonButton link-to="/checkout" center-button>
CHECKOUT
</CommonButton>
</template>
</div>
<h2 v-else class="mt-64 text-3xl text-center">Cart is currently empty</h2>
</template>

Expand All @@ -21,56 +27,43 @@
* Vue.js component for handling the logic of removing a product from the cart and updating the cart state.
*
* @module CartContents
* @param {Object} props - Object containing the component's properties.
* @param {Boolean} props.showCheckoutButton - Determines whether the checkout button should be shown or not.
* @returns {Object} The Vue.js component object.
*/
import GET_CART_QUERY from "@/apollo/queries/GET_CART_QUERY.gql";
import UPDATE_CART_MUTATION from "@/apollo/mutations/UPDATE_CART_MUTATION.gql";

import { computed, ref, onMounted } from 'vue';
import { useCart } from "@/store/useCart";
import CommonButton from '@/components/common/CommonButton.vue';

const cart = useCart();
const isLoading = ref(true);
const error = ref(null);

defineProps({
showCheckoutButton: { type: Boolean, required: false, default: false },
});

const { data } = await useAsyncQuery(GET_CART_QUERY);
const cartItems = computed(() => cart.cart);

/**
* Handles the removal of a product.
*
* @param {Object} product - The product to be removed.
* @param {string} key - The key of the product to be removed.
*/
const handleRemoveProduct = (product) => {
const updatedItems = [];

const { key } = product;

updatedItems.push({
key,
quantity: 0,
});

const variables = {
input: {
items: updatedItems,
},
};

cart.removeProductFromCart(product);

const { mutate, onDone, onError } = useMutation(UPDATE_CART_MUTATION, {
variables,
});

mutate(variables);

onDone(() => {
document.location = "/cart";
});
const handleRemoveProduct = async (key) => {
try {
await cart.removeProductFromCart(key);
} catch (error) {
console.error('Error removing product from cart:', error);
// Optionally, you can add a user-friendly notification here
// without exposing the error details
}
};

onMounted(async () => {
try {
await cart.refetch();
} catch (err) {
console.error('Error fetching cart:', err);
error.value = err;
} finally {
isLoading.value = false;
}
});
</script>

<style scoped>
Expand Down
16 changes: 10 additions & 6 deletions components/Cart/CartItem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</div>
<div class="item">
<span class="block mt-2 font-extrabold">Name: <br /></span>
<span class="item-content">{{ product.product.node.name }}</span>
<span class="item-content">{{ product.product.name }}</span>
</div>
<div class="item">
<span class="block mt-2 font-extrabold">Quantity: <br /></span>
Expand All @@ -25,7 +25,7 @@
</div>
<div class="item">
<span class="block mt-2 font-extrabold">Subtotal: <br /></span>
<span class="item-content">{{ formatPrice(`${product.total}`) }}</span>
<span class="item-content">{{ formatPrice(product.total) }}</span>
</div>
</div>
</template>
Expand All @@ -37,13 +37,16 @@
* @component CartItem
*
* @prop {Object} product - The product object containing information about the product.
* @prop {string} product.name - The name of the product.
* @prop {Object} product.product - The product details.
* @prop {string} product.product.name - The name of the product.
* @prop {number} product.quantity - The quantity of the product.
* @prop {number} product.total - The subtotal of the product.
* @prop {string} product.total - The subtotal of the product.
* @prop {string} product.key - The unique key for the cart item.
*
* @emits CartItem#remove - Emitted when the remove button is clicked.
*/

import { ref } from 'vue';
import { formatPrice } from "@/utils/functions";

const isRemoving = ref(false);
Expand All @@ -58,10 +61,11 @@ const props = defineProps({
const emit = defineEmits(["remove"]);

/**
* Emits a "remove" event with the `product` prop as the payload.
* Emits a "remove" event with the product's key as the payload.
*/
const emitRemove = () => {
emit("remove", props.product);
isRemoving.value = true;
emit("remove", props.product.key);
};
</script>

Expand Down
87 changes: 26 additions & 61 deletions components/Layout/LayoutCart.vue
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
<template>
<div v-if="remoteError">
<span class="text-xl text-red-500"
>Error fetching cart. Please refresh the page.</span
>
</div>
<div v-else class="mt-4 lg:mt-0">
<NuxtLink to="/cart">
<div class="mt-4 lg:mt-0">
<div v-if="isLoading">
<span class="text-xl text-gray-500">Loading cart...</span>
</div>
<div v-else-if="error">
<span class="text-xl text-red-500">
Error fetching cart. Please refresh the page.
</span>
</div>
<NuxtLink v-else to="/cart">
<transition name="cart">
<span
v-if="cartLength && !loading"
v-if="cartLength > 0"
class="text-xl text-white no-underline lg:text-black is-active"
>
<span class="hidden lg:block">
Expand All @@ -29,14 +32,14 @@
</span>
</transition>
<transition name="cart">
<div v-if="cartLength && !loading">
<div v-if="cartLength > 0">
<span
class="absolute w-6 h-6 pb-2 ml-16 -mt-12 text-center text-black bg-white lg:text-white lg:bg-black rounded-full lg:ml-14"
>
{{ cartLength }}
</span>
<span class="text-white lg:text-black">
Total: {{ formatPrice(`${subTotal}`) }}
Total: {{ formatPrice(cartSubtotal) }}
</span>
</div>
</transition>
Expand All @@ -45,62 +48,24 @@
</template>

<script setup>
import { ref, onBeforeMount, computed, watch } from "vue";

import GET_CART_QUERY from "@/apollo/queries/GET_CART_QUERY.gql";
import { getCookie } from "@/utils/functions";
import { ref, computed, onMounted } from "vue";
import { useCart } from "@/store/useCart";
import { formatPrice } from "@/utils/functions";

const cart = useCart();
const cartChanged = ref(false);
const loading = ref(true);
const remoteError = ref(false);

const { data, error, pending, execute } = useAsyncQuery(GET_CART_QUERY, {
fetchPolicy: "cache-and-network",
});

const cartContents = computed(() => data.value?.cart?.contents?.nodes || []);
const cartLength = computed(() =>
cartContents.value.reduce((total, product) => total + product.quantity, 0)
);
const subTotal = computed(() =>
cartContents.value.reduce(
(total, product) => total + Number(product.total.replace(/[^0-9.-]+/g, "")),
0
)
);

// Watch for changes in the cart quantity and set a flag if it changes
watch(cartLength, (newLength, oldLength) => {
if (newLength !== oldLength) {
cartChanged.value = true;
}
});

// Execute the query initially
onBeforeMount(() => {
execute();
});
const isLoading = ref(true);
const error = ref(null);

// When the component is mounted, stop the loading state
loading.value = false;
const cartLength = computed(() => cart.cartQuantity);
const cartSubtotal = computed(() => cart.cartSubtotal);

// Watch for the cartChanged flag and execute the query when it changes
watch(cartChanged, (newValue) => {
if (
newValue &&
process.client &&
!pending.value &&
getCookie("woo-session")
) {
execute();
cartChanged.value = false; // Reset the flag after executing the query
onMounted(async () => {
try {
await cart.refetch();
} catch (err) {
error.value = err;
} finally {
isLoading.value = false;
}
});

// Watch for errors from the Apollo query
watch(error, (newError) => {
remoteError.value = !!newError;
});
</script>
24 changes: 13 additions & 11 deletions components/Products/ProductsSingleProduct.vue
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,14 @@
@common-button-click="addProductToCart(data.product)"
:is-loading="isLoading"
>
ADD TO CART</CommonButton
>
ADD TO CART
</CommonButton>
</div>
</div>
</div>
</div>
</section>
<Toast ref="toast" />
</template>
</template>

Expand All @@ -75,13 +76,13 @@
* @prop {string} slug - The slug of the product to display.
*/

import { ref, watch } from "vue";
import { ref, watch, computed } from "vue";

import GET_SINGLE_PRODUCT_QUERY from "@/apollo/queries/GET_SINGLE_PRODUCT_QUERY.gql";
import ADD_TO_CART_MUTATION from "@/apollo/mutations/ADD_TO_CART_MUTATION.gql";

import ProductImage from "@/components/Products/ProductImage.vue";
import ProductPrice from "@/components/Products/ProductPrice.vue";
import Toast from "@/components/common/Toast.vue";

import { stripHTML, filteredVariantName } from "@/utils/functions";

Expand All @@ -92,6 +93,7 @@ const cart = useCart();
const isLoading = computed(() => cart.loading);

const selectedVariation = ref(); // TODO Pass this value to addProductToCart()
const toast = ref(null);

const props = defineProps({
id: { type: String, required: true },
Expand Down Expand Up @@ -119,12 +121,12 @@ watch(
* @return {Promise<void>} A Promise that resolves when the product has been successfully added to the cart.
*/
const addProductToCart = async (product) => {
await cart.addToCart(product);

watchEffect(() => {
if (isLoading.value === false) {
window.location.reload();
}
});
try {
await cart.addToCart(product);
toast.value.show();
} catch (error) {
console.error('Error adding product to cart:', error);
// You might want to show an error message to the user here
}
};
</script>
Loading