@@ -96,7 +96,7 @@ const AddToCart = ({
9696 variationId,
9797 fullWidth = false ,
9898} : IProductRootObject ) => {
99- const { setCart } = useContext ( CartContext ) ;
99+ const { updateCart } = useContext ( CartContext ) ;
100100 const [ requestError , setRequestError ] = useState < boolean > ( false ) ;
101101
102102 const productId = product ?. databaseId ? product ?. databaseId : variationId ;
@@ -107,20 +107,14 @@ const AddToCart = ({
107107 } ;
108108
109109 // Get cart data query
110- const { data , refetch } = useQuery ( GET_CART , {
110+ const { refetch } = useQuery ( GET_CART , {
111111 notifyOnNetworkStatusChange : true ,
112- onCompleted : ( ) => {
113- // Update cart in the localStorage.
112+ onCompleted : ( data ) => {
113+ // Update cart in the localStorage and React Context .
114114 const updatedCart = getFormattedCart ( data ) ;
115-
116- if ( ! updatedCart ) {
117- return ;
115+ if ( updatedCart ) {
116+ updateCart ( updatedCart ) ;
118117 }
119-
120- localStorage . setItem ( 'woocommerce-cart' , JSON . stringify ( updatedCart ) ) ;
121-
122- // Update cart data in React Context.
123- setCart ( updatedCart ) ;
124118 } ,
125119 } ) ;
126120
@@ -129,29 +123,33 @@ const AddToCart = ({
129123 variables : {
130124 input : productQueryInput ,
131125 } ,
132-
133- onCompleted : ( ) => {
134- // Update the cart with new values in React context.
135- refetch ( ) ;
126+ onCompleted : ( data ) => {
127+ // Immediately update the cart with new values
128+ const updatedCart = getFormattedCart ( data ) ;
129+ if ( updatedCart ) {
130+ updateCart ( updatedCart ) ;
131+ }
136132 } ,
137-
138133 onError : ( ) => {
139134 setRequestError ( true ) ;
140135 } ,
141136 } ) ;
142137
143- const handleAddToCart = ( ) => {
144- addToCart ( ) ;
145- // Refetch cart after 2 seconds
146- setTimeout ( ( ) => {
147- refetch ( ) ;
148- } , 2000 ) ;
138+ const handleAddToCart = async ( ) => {
139+ try {
140+ await addToCart ( ) ;
141+ // Refetch cart immediately after adding to cart
142+ await refetch ( ) ;
143+ } catch ( error ) {
144+ console . error ( 'Error adding to cart:' , error ) ;
145+ setRequestError ( true ) ;
146+ }
149147 } ;
150148
151149 return (
152150 < >
153151 < Button
154- handleButtonClick = { ( ) => handleAddToCart ( ) }
152+ handleButtonClick = { handleAddToCart }
155153 buttonDisabled = { addToCartLoading || requestError }
156154 fullWidth = { fullWidth }
157155 >
0 commit comments