Clear Shopify Cart without Page Reload with Alpine JS

Mark Mead, shopifyalpinejsjavascriptfetchapi
Back

Recently, I've been using a lot of Alpine JS when developing Shopify themes and so far it's worked very well.

Thanks to the latest version of Alpine JS (version 3) we now have access to Alpine JS stores by default! 🥳

Alpine JS Stores Documentation

This means that we can create a source of truth for particular state management, in this case the Shopify cart.

Let's create a new Alpine JS store called "cart" that we will place in either assets/theme.js or layouts/theme.liquid.

💡

When using a JavaScript file then you will need to import and start Alpine JS.

Using Alpine JS in a JavaScript File

Here's our Alpine JS store for the cart.

Alpine.store('cart', {
  data: null,

  clearCart() {
    fetch('/cart/clear.js, { method: 'POST' })
      .then((response) => response.ok && this.getCart())
  },

  getCart() {
    fetch('/cart.js')
      .then((response) => response.json())
      .then((data) => this.data = data)
      .catch((error) => console.error(error))
  }
})

Let's breakdown what this is doing.

IDTypeDescription
dataVariableKeeps all the cart data that is set from getCart
clearCartFunctionClears the cart and then calls getCart once finished
getCartFunctionGets the current cart and saves it to the data variable

Once question you might have is why do we call getCart after clearing? This is so we can reset the data variable.

There's another approach to doing this with response.ok && this.cart = null but the approach is your choice, they're both very quick.

The last part is the HTML, thankfully Alpine JS exposes the store in a $store variable. Therefore, we can create a button that clears the cart with the following code.

<button x-data type="button" @click="$store.cart.clearCart">Clear Cart</button>

And that's that. You can now take $store.cart.clearCart and place that where you need to clear the cart in your Shopify store.

💡

If the clear cart button is within a form remember to include type="button" to stop the form from being submitted on click.

If you are using this on the cart page or within a cart popup/drawer then you'll want to handle the UI to show the user that the cart has been emptied.

© Mark Mead.RSS