Skip to content

Commit 863e402

Browse files
committed
Update AddToCart.component.tsx
1 parent 7b1dc36 commit 863e402

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

src/components/Product/AddToCart.component.tsx

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -123,23 +123,29 @@ const AddToCart = ({
123123
},
124124
});
125125

126-
const handleAddToCart = () => {
127-
// Optimistically update cart count
128-
if (cart) {
129-
setCart({
130-
...cart,
131-
totalProductsCount: cart.totalProductsCount + 1,
132-
products: [...cart.products]
133-
});
134-
} else {
135-
setCart({
136-
products: [],
137-
totalProductsCount: 1,
138-
totalProductsPrice: 0
139-
});
126+
const handleAddToCart = async () => {
127+
try {
128+
// First attempt the server update
129+
await addToCart();
130+
131+
// Only update local state if server update succeeds
132+
if (cart) {
133+
setCart({
134+
...cart,
135+
totalProductsCount: cart.totalProductsCount + 1,
136+
products: [...cart.products]
137+
});
138+
} else {
139+
setCart({
140+
products: [],
141+
totalProductsCount: 1,
142+
totalProductsPrice: 0
143+
});
144+
}
145+
} catch (error) {
146+
console.error('Failed to add to cart:', error);
147+
setRequestError(true);
140148
}
141-
142-
addToCart();
143149
};
144150

145151
return (

0 commit comments

Comments
 (0)