Trigger wc_fragment_refresh from React

For my wife’s cabinet business, I’m working on a replacement for the category archive page that’s built with React. I’ve been able to add items to the cart over the Store REST API but the mini-cart and header count in my theme didn’t update unless the page is refreshed. It’s important that these update automatically and quickly to give feedback to customers.

The mechanism that updates these is triggered with jQuery so how does that work from inside React? Turns out, this is actually pretty easy to do. In my method that’s triggered by clicking the add to cart button, I just insert the jQuery code after the add-to-cart is successful.

	const getSelectedProduct = async () => {
		setLoading('loading');
		await addToCart(productToAdd[0].id, quantity);
		setLoading('');
		jQuery(document.body).trigger('wc_fragment_refresh');
	};

That will trigger the cart fragments to refresh from inside React. This helps me out since I only have to replace the parts of the theme I really need to with React. I don’t have to create a complete React based site to get the advantages that I need.


Leave a Reply

%d bloggers like this: