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 = () => {
119119
120120 // Optimistically update local state
121121 if ( cart ) {
122+ const oldProduct = cart . products . find ( ( p : Product ) => p . cartKey === item . key ) ;
123+ const oldQty = oldProduct ?. qty || 0 ;
122124 const updatedProducts = cart . products . map ( ( p : Product ) =>
123125 p . cartKey === item . key ? { ...p , qty : newQty } : p
124126 ) ;
127+
128+ // Calculate new total count
129+ const qtyDiff = newQty - oldQty ;
130+ const newTotalCount = cart . totalProductsCount + qtyDiff ;
131+
125132 setCart ( {
126133 ...cart ,
127134 products : updatedProducts ,
135+ totalProductsCount : newTotalCount
128136 } ) ;
129137 }
130138
Original file line number Diff line number Diff line change @@ -92,7 +92,7 @@ const AddToCart = ({
9292 variationId,
9393 fullWidth = false ,
9494} : IProductRootObject ) => {
95- const { setCart, isLoading : isCartLoading } = useCartStore ( ) ;
95+ const { cart , setCart, isLoading : isCartLoading } = useCartStore ( ) ;
9696 const [ requestError , setRequestError ] = useState < boolean > ( false ) ;
9797
9898 const productId = product ?. databaseId ? product ?. databaseId : variationId ;
@@ -124,6 +124,21 @@ const AddToCart = ({
124124 } ) ;
125125
126126 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+
127142 addToCart ( ) ;
128143 } ;
129144
You can’t perform that action at this time.
0 commit comments