@@ -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 , isLoading : isCartLoading } = 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,36 +129,33 @@ 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 } ,
137+
132138 onError : ( ) => {
133139 setRequestError ( true ) ;
134140 } ,
135141 } ) ;
136142
137- const handleAddToCart = async ( ) => {
138- try {
139- await addToCart ( ) ;
140- // Refetch cart immediately after adding to cart
141- await refetch ( ) ;
142- } catch ( error ) {
143- setRequestError ( true ) ;
144- }
143+ const handleAddToCart = ( ) => {
144+ addToCart ( ) ;
145+ // Refetch cart after 2 seconds
146+ setTimeout ( ( ) => {
147+ refetch ( ) ;
148+ } , 2000 ) ;
145149 } ;
146150
147151 return (
148152 < >
149153 < Button
150- handleButtonClick = { handleAddToCart }
151- buttonDisabled = { addToCartLoading || requestError }
154+ handleButtonClick = { ( ) => handleAddToCart ( ) }
155+ buttonDisabled = { addToCartLoading || requestError || isCartLoading }
152156 fullWidth = { fullWidth }
153157 >
154- KJØP
158+ { isCartLoading ? 'Loading...' : ' KJØP' }
155159 </ Button >
156160 </ >
157161 ) ;
0 commit comments