File tree Expand file tree Collapse file tree 2 files changed +24
-1
lines changed Expand file tree Collapse file tree 2 files changed +24
-1
lines changed Original file line number Diff line number Diff line change @@ -119,12 +119,20 @@ const CartContents = () => {
119
119
120
120
// Optimistically update local state
121
121
if ( cart ) {
122
+ const oldProduct = cart . products . find ( ( p : Product ) => p . cartKey === item . key ) ;
123
+ const oldQty = oldProduct ?. qty || 0 ;
122
124
const updatedProducts = cart . products . map ( ( p : Product ) =>
123
125
p . cartKey === item . key ? { ...p , qty : newQty } : p
124
126
) ;
127
+
128
+ // Calculate new total count
129
+ const qtyDiff = newQty - oldQty ;
130
+ const newTotalCount = cart . totalProductsCount + qtyDiff ;
131
+
125
132
setCart ( {
126
133
...cart ,
127
134
products : updatedProducts ,
135
+ totalProductsCount : newTotalCount
128
136
} ) ;
129
137
}
130
138
Original file line number Diff line number Diff line change @@ -92,7 +92,7 @@ const AddToCart = ({
92
92
variationId,
93
93
fullWidth = false ,
94
94
} : IProductRootObject ) => {
95
- const { setCart, isLoading : isCartLoading } = useCartStore ( ) ;
95
+ const { cart , setCart, isLoading : isCartLoading } = useCartStore ( ) ;
96
96
const [ requestError , setRequestError ] = useState < boolean > ( false ) ;
97
97
98
98
const productId = product ?. databaseId ? product ?. databaseId : variationId ;
@@ -124,6 +124,21 @@ const AddToCart = ({
124
124
} ) ;
125
125
126
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
+ } ) ;
140
+ }
141
+
127
142
addToCart ( ) ;
128
143
} ;
129
144
You can’t perform that action at this time.
0 commit comments