Skip to content

Commit fe1a947

Browse files
authored
Merge pull request #1519 from w3bdesign/develop
Refactor cart store to improve Apollo cache updates
2 parents 40c9177 + 64078df commit fe1a947

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

store/useCart.js

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { defineStore } from "pinia";
22
import { computed, ref, watch } from "vue";
3-
import { useMutation } from "@vue/apollo-composable";
3+
import { useQuery, useMutation } from "@vue/apollo-composable";
44

55
import ADD_TO_CART_MUTATION from "@/apollo/mutations/ADD_TO_CART_MUTATION.gql";
66
import UPDATE_CART_MUTATION from "@/apollo/mutations/UPDATE_CART_MUTATION.gql";
@@ -13,11 +13,18 @@ export const useCart = defineStore(
1313
const cartTotals = ref({});
1414

1515
const {
16-
data: cartData,
17-
pending: loading,
16+
result: cartData,
17+
loading,
1818
error,
19-
refresh: refetchCart,
20-
} = useAsyncQuery(GET_CART_QUERY);
19+
refetch: refetchCart,
20+
} = useQuery(
21+
GET_CART_QUERY,
22+
{},
23+
{
24+
fetchPolicy: "cache-and-network",
25+
notifyOnNetworkStatusChange: true,
26+
},
27+
);
2128

2229
watch(
2330
cartData,
@@ -62,15 +69,9 @@ export const useCart = defineStore(
6269
};
6370

6471
const { mutate: addToCartMutation, loading: addToCartLoading } =
65-
useMutation(ADD_TO_CART_MUTATION, {
66-
refetchQueries: [{ query: GET_CART_QUERY }],
67-
awaitRefetchQueries: true,
68-
});
72+
useMutation(ADD_TO_CART_MUTATION);
6973
const { mutate: updateCartMutation, loading: updateCartLoading } =
70-
useMutation(UPDATE_CART_MUTATION, {
71-
refetchQueries: [{ query: GET_CART_QUERY }],
72-
awaitRefetchQueries: true,
73-
});
74+
useMutation(UPDATE_CART_MUTATION);
7475

7576
const addToCart = async (product, quantity = 1) => {
7677
try {
@@ -80,8 +81,12 @@ export const useCart = defineStore(
8081
quantity: quantity,
8182
},
8283
});
84+
// Force refetch to ensure cache is updated
85+
await refetchCart();
8386
} catch (err) {
8487
console.error("Error adding to cart:", err);
88+
// Still refetch on error to ensure consistency
89+
await refetchCart();
8590
}
8691
};
8792

@@ -92,8 +97,12 @@ export const useCart = defineStore(
9297
items: Array.isArray(key) ? key : [{ key, quantity }],
9398
},
9499
});
100+
// Force refetch to ensure cache is updated
101+
await refetchCart();
95102
} catch (err) {
96103
console.error("Error updating cart item quantity:", err);
104+
// Still refetch on error to ensure consistency
105+
await refetchCart();
97106
}
98107
};
99108

0 commit comments

Comments
 (0)