Skip to content

Commit

Permalink
fix(cart): ensure cart sync occurs only when local storage contains i…
Browse files Browse the repository at this point in the history
…tems
  • Loading branch information
jwinr committed Sep 27, 2024
1 parent fb693a4 commit abab209
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
6 changes: 3 additions & 3 deletions src/components/Shopping/AddToCartButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
`

Expand Down Expand Up @@ -47,7 +47,7 @@ const AddToCartButton: React.FC<AddToCartButtonProps> = ({
disabled={loading || internalLoading}
aria-label={`Add ${productName} to cart`}
>
<ButtonText loading={loading || internalLoading}>Add to cart</ButtonText>
<ButtonText $loading={loading || internalLoading}>Add to cart</ButtonText>
{(loading || internalLoading) && <LoaderSpin isLoading={true} />}
</Button>
)
Expand Down
26 changes: 21 additions & 5 deletions src/context/CartContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand Down

0 comments on commit abab209

Please sign in to comment.