File tree Expand file tree Collapse file tree 1 file changed +22
-16
lines changed
Expand file tree Collapse file tree 1 file changed +22
-16
lines changed Original file line number Diff line number Diff 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 (
You can’t perform that action at this time.
0 commit comments