Skip to main content

Magento 2 - Triggering totals refresh in cart and in the mini-cart

· 2 min read

In this tutorial, we will show how to trigger a refresh in the mini-cart and the cart totals block.

What is the totals block?

The totals block is the block that displays totals - subtotal, discount, shipping rates, taxes, and grand total.

Totals block in the Magento 2 cart

How to cause the mini-cart and the totals block to refresh?

Sometimes, when working on JavaScript code that changes totals in Magento, you might want to refresh the mini-cart or the cart totals block.

For example, when we worked on our Free Gift module for Magento 2, we needed to refresh the mini-cart and the cart totals block once the customer added the gift product. So, let's see how we did that.

In order to do that, we used the following piece of code in our JS:

cartCache.clear('totals');
customerData.reload(['cart'], false);

For the context, here is the full code snippet of our JS file. You can see that after a successful AJAX response, we trigger the refresh of the mini cart and the cart totals.

if the user is on the cart page, both the mini-cart and the cart totals will refresh. If the user is on another page, only the mini-cart will refresh.

define([
'jquery',
'Magento_Ui/js/modal/modal',
'Magento_Checkout/js/model/cart/cache',
'Magento_Customer/js/customer-data'
], function (
$,
modal,
cartCache,
customerData
) {
'use strict';

return {
sendPromoAddToCartRequest: function (ajaxUrl, params, modalSelector = null, modalOptions = null) {
$.ajax({
url: ajaxUrl,
type: 'post',
data: params,
showLoader: true,
dataType: 'json',
success: function (response) {
if(!$.isEmptyObject(response)){
cartCache.clear('totals');
customerData.reload(['cart'], false);
}
}
});
},
}
});

The totals block in Magento 2 cart is refreshing

Summing up

We just saw how to cause the totals block to refresh.