@@ -90,12 +90,13 @@ export interface IProductRootObject {
90
90
* @param {number } variationId // Variation ID
91
91
* @param {boolean } fullWidth // Whether the button should be full-width
92
92
*/
93
+
93
94
const AddToCart = ( {
94
95
product,
95
96
variationId,
96
97
fullWidth = false ,
97
98
} : IProductRootObject ) => {
98
- const { updateCart } = useContext ( CartContext ) ;
99
+ const { setCart , isLoading : isCartLoading } = useContext ( CartContext ) ;
99
100
const [ requestError , setRequestError ] = useState < boolean > ( false ) ;
100
101
101
102
const productId = product ?. databaseId ? product ?. databaseId : variationId ;
@@ -106,14 +107,20 @@ const AddToCart = ({
106
107
} ;
107
108
108
109
// Get cart data query
109
- const { refetch } = useQuery ( GET_CART , {
110
+ const { data , refetch } = useQuery ( GET_CART , {
110
111
notifyOnNetworkStatusChange : true ,
111
- onCompleted : ( data ) => {
112
- // Update cart in the localStorage and React Context .
112
+ onCompleted : ( ) => {
113
+ // Update cart in the localStorage.
113
114
const updatedCart = getFormattedCart ( data ) ;
114
- if ( updatedCart ) {
115
- updateCart ( updatedCart ) ;
115
+
116
+ if ( ! updatedCart ) {
117
+ return ;
116
118
}
119
+
120
+ localStorage . setItem ( 'woocommerce-cart' , JSON . stringify ( updatedCart ) ) ;
121
+
122
+ // Update cart data in React Context.
123
+ setCart ( updatedCart ) ;
117
124
} ,
118
125
} ) ;
119
126
@@ -122,36 +129,33 @@ const AddToCart = ({
122
129
variables : {
123
130
input : productQueryInput ,
124
131
} ,
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 ( ) ;
131
136
} ,
137
+
132
138
onError : ( ) => {
133
139
setRequestError ( true ) ;
134
140
} ,
135
141
} ) ;
136
142
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 ) ;
145
149
} ;
146
150
147
151
return (
148
152
< >
149
153
< Button
150
- handleButtonClick = { handleAddToCart }
151
- buttonDisabled = { addToCartLoading || requestError }
154
+ handleButtonClick = { ( ) => handleAddToCart ( ) }
155
+ buttonDisabled = { addToCartLoading || requestError || isCartLoading }
152
156
fullWidth = { fullWidth }
153
157
>
154
- KJØP
158
+ { isCartLoading ? 'Loading...' : ' KJØP' }
155
159
</ Button >
156
160
</ >
157
161
) ;
0 commit comments