Magento 2: How to update the total using JS

How to update total using JS in magento 2 - Sb Dev Blog

How to update the total using JS Let’s check how we can achieve this in Magento 2. We have updated Mini Cart using sections.xml and JS in the post: https://sbdevblog.com/magento-2-how-to-update-mini-cart/

Like the mini-cart, sometimes we need to update totals in the cart and checkout summary. We will see how we can update totals in the cart and checkout summary using JS.

Total is an essential part of our cart and checkout summary. The conversion from the cart to the order depends on the total as well. Therefore, the Total must be visible and updated from time to time on all events that relate to the totals and pricing, like custom tax or discount added using custom functionality. We often implement tasks that relate to pricing. Hence, we have to update the total as well. so Let’s check out this in this post.

We need to inject the JS given below into the JS file from which we need to update the total.

'Magento_Checkout/js/model/cart/totals-processor/default',
'Magento_Checkout/js/model/cart/cache'

Then we just need to clear the cache, which belongs to the total. To clear the cache of the total, we need to add the below line into our JS.

cartCache.set('totals',null);

Once we clear the cache of the total, we just need to trigger the function to get the updated total in our cart and checkout summary.

To get the updated total, we just need to call estmiateTotals() of the injected total-processor JS.

total.estimateTotals();

Let’s have a look at an example.

Magento 2: How to update the total using JS

define(
    [
        'ko',
        'jquery',
        'Magento_Checkout/js/model/cart/totals-processor/default',
        'Magento_Checkout/js/model/cart/cache'
    ],
    function (ko, $, total, cartCache) {
        'use strict';
        return Component.extend({
            triggerUpdate:function () {
                cartCache.set('totals',null);
                total.estimateTotals();
            },
            updateTheTotal: function() {
              this.triggerUpdate();
            }
        });
    }
);

That’s it. It is pretty easy to trigger the total in our cart. Thanks for reading the post.

You may check out the git repository: http://github.com/sbdevblog/

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

2 thoughts on “Magento 2: How to update the total using JS

Leave a Reply

Your email address will not be published. Required fields are marked *