Automatically update the UI when an item is removed from the cart

SquareMarket
Tourist
7 0 0

In my cart template I have a script that checks if you have more than once collection in it, and if so, remove the checkout button.  What I want to do is to do that check each time an item is removed from the cart. Right now I have to manually refresh the page to see the change. How do I automatically update the component?

 

{%- assign item_collections = '' -%}
			{%- for line_item in cart.items -%}
  				{%- for collection in line_item.product.collections -%}
					{%- assign item_collections = item_collections | append: collection.title | append: ',' -%}
  				{%- endfor -%}
			{%- endfor -%}

		{%- assign item_collections = item_collections | split: ',' | uniq -%}

		{%- if item_collections.size > 1 -%}
          Checkout cannot contain items from more than 1 supplier. Please remove the items and refresh the page </p>
		{%- else -%}
                 <div class="cart__checkout-wrapper">
            <button type="submit" name="checkout" data-terms-required="{{ settings.cart_terms_conditions_enable }}" class="btn cart__checkout">
              {{ 'cart.general.checkout' | t }}
            </button>

            {% if additional_checkout_buttons and settings.cart_additional_buttons %}
              <div class="additional-checkout-buttons additional-checkout-buttons--vertical">{{ content_for_additional_checkout_buttons }}</div>
            {% endif %}
          </div>
			{%- endif -%}
0 Likes

@SquareMarket 

This is more complex than it meets the eyes. 

The piece of code you're sharing is not responsible for real time updates - real time updates are done via Javascript. Liquid is able to set an initial value, however, it's unable to keep track of changes nor update the UI.

Assuming that you're using a theme (and not custom coding one from scratch): every Shopify theme has an "add to cart" code structure built-in in its theme.js. They can track whether an item was added, removed, updated, etc.

In Debut, for instance, there is the "_additemToCart" function. It's responsible to track whenever an item is added to cart. As aforementioned, there are multitudinous functions with the most varied functionalities: to track whether the item was removed, quantity changed, etc.

diego_ezfy_0-1626117115594.png

You'd need to find those functions and wire them up with your own custom code.

There's also CartJS which is a simplified Javascript library for Shopify carts, but I am not sure whether it's able to keep track of your current cart, it may be worth it taking a look into that.

Kind regards,
Dieog

◦ Slideshow section not looking good? Try the Slideshow (PRO) section. No apps required.
◦ Product page images slider for free themes (w/ 20+ customization options): Minimal | Debut | Brooklyn | Supply
◦ If my answer helps you please click on like and Accept as solution!
0 Likes