Skip to content

Commit fe009cd

Browse files
committed
Refactor cart store to improve Apollo cache updates
Switches from useAsyncQuery to useQuery for cart data with improved fetch policies. Removes refetchQueries from mutations and instead explicitly refetches the cart after add/update operations to ensure cache consistency. Also updates error handling to always refetch the cart on mutation errors.
1 parent 11050f4 commit fe009cd

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

store/useCart.js

Lines changed: 18 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,14 @@ 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(GET_CART_QUERY, {}, {
21+
fetchPolicy: 'cache-and-network',
22+
notifyOnNetworkStatusChange: true,
23+
});
2124

2225
watch(
2326
cartData,
@@ -62,15 +65,9 @@ export const useCart = defineStore(
6265
};
6366

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

7572
const addToCart = async (product, quantity = 1) => {
7673
try {
@@ -80,8 +77,12 @@ export const useCart = defineStore(
8077
quantity: quantity,
8178
},
8279
});
80+
// Force refetch to ensure cache is updated
81+
await refetchCart();
8382
} catch (err) {
8483
console.error("Error adding to cart:", err);
84+
// Still refetch on error to ensure consistency
85+
await refetchCart();
8586
}
8687
};
8788

@@ -92,8 +93,12 @@ export const useCart = defineStore(
9293
items: Array.isArray(key) ? key : [{ key, quantity }],
9394
},
9495
});
96+
// Force refetch to ensure cache is updated
97+
await refetchCart();
9598
} catch (err) {
9699
console.error("Error updating cart item quantity:", err);
100+
// Still refetch on error to ensure consistency
101+
await refetchCart();
97102
}
98103
};
99104

0 commit comments

Comments
 (0)