1

I am currently developing a small block for WordPress/WooCommerce and now I have a problem that I can't solve easily.

To summarize:
I am looking for a way to update my block in the frontend when changes have been made in the cart block (e.g. the user increases the number of a product in the shopping cart).

My block is currently set up as a server-side render block and the corresponding markup is generated by PHP via render_callback and then output.

Is there a way to update the block in the frontend after an event from the cart block? And if not, what methods would there be to reach the target?

Thanks in advance.

Cheers 🍺

1 Answer 1

2

Something like this should work:

const {select, subscribe} = window.wp.data;
const cartStoreKey = window.wc.wcBlocksData.CART_STORE_KEY;
const unsub = subscribe( onCartChange, cartStoreKey );

function onCartChange() {
    const cart = select( cartStoreKey ).getCartData();
    console.log( '¡ cart change !', cart );
}

The block’s frontend script should have the woocommerce script’s handle as a dependency so the window.wc.wcBlocksData will be defined by the time the block’s script executes. According to the WC store docs the handle is wc-blocks-data-store.

In case you haven’t seen it you might want to check out the Interactivity API if the updates you want to make to the markup are non-trivial.

1
  • Thank you. That was the part I was missing. I should also mention that in my solution, after updating the cart block, I render my block on the PHP side and then replace the content of the old block with the content of the new block via JS. I realize the whole thing by adding my own data via the Store API.
    – HackePeter
    Commented Mar 13 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.