@@ -90,12 +90,13 @@ export interface IProductRootObject {
9090 * @param {number } variationId // Variation ID
9191 * @param {boolean } fullWidth // Whether the button should be full-width
9292 */
93+
9394const AddToCart = ( {
9495 product,
9596 variationId,
9697 fullWidth = false ,
9798} : IProductRootObject ) => {
98- const { updateCart } = useContext ( CartContext ) ;
99+ const { setCart , cart } = useContext ( CartContext ) ;
99100 const [ requestError , setRequestError ] = useState < boolean > ( false ) ;
100101
101102 const productId = product ?. databaseId ? product ?. databaseId : variationId ;
@@ -106,14 +107,20 @@ const AddToCart = ({
106107 } ;
107108
108109 // Get cart data query
109- const { refetch } = useQuery ( GET_CART , {
110+ const { data , refetch } = useQuery ( GET_CART , {
110111 notifyOnNetworkStatusChange : true ,
111- onCompleted : ( data ) => {
112- // Update cart in the localStorage and React Context .
112+ onCompleted : ( ) => {
113+ // Update cart in the localStorage.
113114 const updatedCart = getFormattedCart ( data ) ;
114- if ( updatedCart ) {
115- updateCart ( updatedCart ) ;
115+
116+ if ( ! updatedCart ) {
117+ return ;
116118 }
119+
120+ localStorage . setItem ( 'woocommerce-cart' , JSON . stringify ( updatedCart ) ) ;
121+
122+ // Update cart data in React Context.
123+ setCart ( updatedCart ) ;
117124 } ,
118125 } ) ;
119126
@@ -122,38 +129,37 @@ const AddToCart = ({
122129 variables : {
123130 input : productQueryInput ,
124131 } ,
125- onCompleted : ( data ) => {
126- // Immediately update the cart with new values
127- const updatedCart = getFormattedCart ( data ) ;
128- if ( updatedCart ) {
129- updateCart ( updatedCart ) ;
130- }
132+
133+ onCompleted : ( ) => {
134+ // Update the cart with new values in React context.
135+ refetch ( ) ;
131136 } ,
132- onError : ( error ) => {
133- console . error ( 'Error adding to cart' ) ;
134- console . error ( error ) ;
137+
138+ onError : ( ) => {
135139 setRequestError ( true ) ;
136140 } ,
137141 } ) ;
138142
139- const handleAddToCart = async ( ) => {
140- try {
141- await addToCart ( ) ;
142- // Refetch cart immediately after adding to cart
143- await refetch ( ) ;
144- } catch ( error ) {
145- setRequestError ( true ) ;
143+ const handleAddToCart = ( ) => {
144+ if ( ! cart ) {
145+ console . log ( 'Cart is not yet initialized. Please wait.' ) ;
146+ return ;
146147 }
148+ addToCart ( ) ;
149+ // Refetch cart after 2 seconds
150+ setTimeout ( ( ) => {
151+ refetch ( ) ;
152+ } , 2000 ) ;
147153 } ;
148154
149155 return (
150156 < >
151157 < Button
152- handleButtonClick = { handleAddToCart }
153- buttonDisabled = { addToCartLoading || requestError }
158+ handleButtonClick = { ( ) => handleAddToCart ( ) }
159+ buttonDisabled = { addToCartLoading || requestError || ! cart }
154160 fullWidth = { fullWidth }
155161 >
156- KJØP
162+ { ! cart ? 'Loading...' : ' KJØP' }
157163 </ Button >
158164 </ >
159165 ) ;
0 commit comments