javascriptjquerywoocommercecheckoutgutenberg-blocks

How to detect errors in the WooCommerce checkout form added with the checkout block?


I have a WooCommerce store that uses a checkout block. I want to track with Google Analytics what WooCommerce checkout fields are empty or are incorrectly filled in. The check should happen after a user clicks the "Pay now" button.

In the old "shortcode checkout" this was very easy to do just by listening to a built-in WooCommerce event and then looking for fields that had woocommerce-invalid-required-field class:

jQuery( document.body ).on( 'checkout_error', function(){...

However, so far, I have not found an equivalent to the "checkout_error" that I can listen to.


Solution

  • In order to detect when there are errors in the form after the user clicks "pay now" button, you need to use the solution below.

    Since "subscription" will be triggered on every interaction with every field, we need to make sure that it only triggers once, after the "pay" button is clicked. I left a comment in its place.

    let pay_btn_clicked = false;
    
    // here you need to write a function that changes the value of "pay_btn_clicked" to true, when the button is clicked
    
    const { subscribe, select } = wp.data;
                
    subscribe(() => {
        const checkoutData = select('wc/store/checkout');
    
        if ( pay_btn_clicked ) {
            if ( checkoutData.hasError() ) {
                console.error('There was an error in checkout');
            } else {
                console.error('There were no errors in checkout');
            }
        }
    
        pay_btn_clicked = false;
    });