From abab20904dae2de4e590be79b1c63ec611067be7 Mon Sep 17 00:00:00 2001 From: jwinr Date: Thu, 26 Sep 2024 21:53:29 -0400 Subject: [PATCH] fix(cart): ensure cart sync occurs only when local storage contains items --- src/components/Shopping/AddToCartButton.tsx | 6 ++--- src/context/CartContext.tsx | 26 +++++++++++++++++---- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/components/Shopping/AddToCartButton.tsx b/src/components/Shopping/AddToCartButton.tsx index 4c96a6b..23c362f 100644 --- a/src/components/Shopping/AddToCartButton.tsx +++ b/src/components/Shopping/AddToCartButton.tsx @@ -11,8 +11,8 @@ interface AddToCartButtonProps { loading?: boolean } -const ButtonText = styled.span<{ loading: boolean }>` - opacity: ${({ loading }) => (loading ? 0 : 1)}; +const ButtonText = styled.span<{ $loading: boolean }>` + opacity: ${({ $loading }) => ($loading ? 0 : 1)}; transition: opacity 0.24s ease-in-out; ` @@ -47,7 +47,7 @@ const AddToCartButton: React.FC = ({ disabled={loading || internalLoading} aria-label={`Add ${productName} to cart`} > - Add to cart + Add to cart {(loading || internalLoading) && } ) diff --git a/src/context/CartContext.tsx b/src/context/CartContext.tsx index a1ab431..ae16d20 100644 --- a/src/context/CartContext.tsx +++ b/src/context/CartContext.tsx @@ -294,13 +294,14 @@ export const CartProvider: React.FC<{ children: ReactNode }> = ({ } const syncLocalCartWithServer = useCallback(async () => { - if (userAttributes && !isSyncing) { + const localCart = JSON.parse( + localStorage.getItem('cart') || '[]' + ) as CartItem[] + + // Only proceed with syncing if the local cart has items + if (userAttributes && !isSyncing && localCart.length > 0) { setIsSyncing(true) try { - const localCart = JSON.parse( - localStorage.getItem('cart') || '[]' - ) as CartItem[] - const token = await getToken() if (!token) { throw new Error(INVALID_JWT_TOKEN_ERROR) @@ -325,6 +326,21 @@ export const CartProvider: React.FC<{ children: ReactNode }> = ({ } }, [userAttributes, isSyncing, fetchCart, getToken]) + useEffect(() => { + const localCart = JSON.parse( + localStorage.getItem('cart') || '[]' + ) as CartItem[] + + // Fetch the cart on component mount + void fetchCart() + + // Sync local cart with server only if there are items + if (localCart.length > 0 && !hasSyncedCart.current) { + void syncLocalCartWithServer() + hasSyncedCart.current = true + } + }, [userAttributes, fetchCart, syncLocalCartWithServer]) + const clearCart = async () => { setLoadingSummary(true) try {