Skip to content
This repository was archived by the owner on Feb 23, 2024. It is now read-only.

Commit ecede2c

Browse files
senadirnerrad
authored andcommitted
Fix bug with cart not updating (#1258)
* fix bug with add to cart * prettier * migrate to Event * prettier * Update assets/js/atomic/components/product/button/index.js update to fix on sequential adds Co-Authored-By: Albert Juhé Lluveras <[email protected]> * Avoid dispatching cart update event on initial mount * add condition to check if Event is defined
1 parent aca460e commit ecede2c

File tree

1 file changed

+26
-0
lines changed
  • assets/js/atomic/components/product/button

1 file changed

+26
-0
lines changed

assets/js/atomic/components/product/button/index.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ const useAddToCart = ( productId ) => {
8080
};
8181
};
8282

83+
const Event = window.Event || {};
84+
8385
const ProductButton = ( { product, className } ) => {
8486
const {
8587
id,
@@ -97,6 +99,7 @@ const ProductButton = ( { product, className } ) => {
9799
} = useAddToCart( id );
98100
const { layoutStyleClassPrefix } = useProductLayoutContext();
99101
const addedToCart = cartQuantity > 0;
102+
const firstMount = useRef( true );
100103
const getButtonText = () => {
101104
if ( Number.isFinite( cartQuantity ) && addedToCart ) {
102105
return sprintf(
@@ -106,6 +109,29 @@ const ProductButton = ( { product, className } ) => {
106109
}
107110
return productCartDetails.text;
108111
};
112+
113+
// This is a hack to trigger cart updates till we migrate to block based card
114+
// that relies on the store, see
115+
// https://github.com/woocommerce/woocommerce-gutenberg-products-block/issues/1247
116+
useEffect( () => {
117+
if ( firstMount.current ) {
118+
firstMount.current = false;
119+
return;
120+
}
121+
// Test if we have our Event defined
122+
if ( Object.entries( Event ).length !== 0 ) {
123+
const event = new Event( 'wc_fragment_refresh', {
124+
bubbles: true,
125+
cancelable: true,
126+
} );
127+
document.body.dispatchEvent( event );
128+
} else {
129+
const event = document.createEvent( 'Event' );
130+
event.initEvent( 'wc_fragment_refresh', true, true );
131+
document.body.dispatchEvent( event );
132+
}
133+
}, [ cartQuantity ] );
134+
109135
const wrapperClasses = classnames(
110136
className,
111137
`${ layoutStyleClassPrefix }__product-add-to-cart`,

0 commit comments

Comments
 (0)