woocommerce/docs/cart-and-checkout-blocks/dom-events.md

3.5 KiB

post_title menu_title tags
Cart and Checkout - DOM events DOM Events reference

Some blocks need to react to certain events in order to display the most up to date data or behave in a certain way. That's the case of the Cart block, for example, that must listen to 'add to cart' events in order to update the cart contents; or the Mini-Cart block, that gets opened every time a product is added to the cart.

WooCommerce core events in WooCommerce Blocks

WooCommerce core uses jQuery events to trigger and listen to certain events, like when a product is added or removed from the cart. In WooCommerce Blocks, we moved away from using jQuery, but we still need to listen to those events. To achieve that, we have a utility named translatejQueryEventToNative() that listens to those jQuery events, and every time one is triggered, it triggers an associated DOM native event (with the wc-blocks_ prefix).

WooCommerce Blocks events

wc-blocks_adding_to_cart

This event is the equivalent to the jQuery event adding_to_cart triggered by WooCommerce core. It indicates that the process of adding a product to the cart was sent to the server, but there is still no indication on whether the product was successfully added or not.

Example usage in WC Blocks: Mini-Cart block listens to this event to append its dependencies.

wc-blocks_added_to_cart

This event is the equivalent to the jQuery event added_to_cart triggered by WooCommerce core. It indicates that the process of adding a product to the cart has finished with success.

Example usage in WC Blocks: Cart and Mini-Cart blocks (via the useStoreCart() hook) listen to this event to know if they need to update their contents.

detail parameters

Parameter Type Default value Description
preserveCartData boolean false Whether Cart data in the store should be preserved. By default, it's false so any wc-blocks_added_to_cart event will invalidate cart data and blocks listening to it will refetch cart data again. However, if the code triggering the event already updates the store (ie: All Products block), it can set preserveCartData: true to avoid the other blocks refetching the data again.

wc-blocks_removed_from_cart

This event is the equivalent to the jQuery event removed_from_cart triggered by WooCommerce core. It indicates that a product has been removed from the cart.

Example usage in WC Blocks: Cart and Mini-Cart blocks (via the useStoreCart() hook) listen to this event to know if they need to update their contents.