You can try the below code.
require([
'Magento_Customer/js/customer-data'
], function (customerData) {
var sections = ['cart'];
customerData.invalidate(sections);
customerData.reload(sections, true);
});
Add to cart Ajax call is given in below js file:
/vendor/magento/module-catalog/view/frontend/web/js/catalog-add-to-cart.js
So we need to override it in your theme like following:
/app/design/frontend/custom_package_name/custom_theme_name/Magento_Catalog/web/js/catalog-add-to-cart.js
Following is default ajax call where we need to add some code:
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: 'post',
dataType: 'json',
beforeSend: function() {
if (self.isLoaderEnabled()) {
$('body').trigger(self.options.processStart);
}
},
success: function(res) {
if (self.isLoaderEnabled()) {
$('body').trigger(self.options.processStop);
}
if (res.backUrl) {
window.location = res.backUrl;
return;
}
if (res.messages) {
$(self.options.messagesSelector).html(res.messages);
}
if (res.minicart) {
$(self.options.minicartSelector).replaceWith(res.minicart);
$(self.options.minicartSelector).trigger('contentUpdated');
}
if (res.product && res.product.statusText) {
$(self.options.productStatusSelector)
.removeClass('available')
.addClass('unavailable')
.find('span')
.html(res.product.statusText);
}
self.enableAddToCartButton(form);
}
});
},
Add below code in beforeSend() function:
/*To hide loader on mini-cart*/
$(".loading-mask").show();
/*****************************/
Add below code in success() function:
/*To hide loader on mini-cart*/
setTimeout(function() {
$(".loading-mask").hide();
}, 3000);
/*******************************/
Like below:
beforeSend: function() {
if (self.isLoaderEnabled()) {
$('body').trigger(self.options.processStart);
}
/*To hide loader on mini-cart*/
$(".loading-mask").show();
/*****************************/
},
success: function(res) {
if (self.isLoaderEnabled()) {
$('body').trigger(self.options.processStop);
}
if (res.backUrl) {
window.location = res.backUrl;
return;
}
if (res.messages) {
$(self.options.messagesSelector).html(res.messages);
}
if (res.minicart) {
$(self.options.minicartSelector).replaceWith(res.minicart);
$(self.options.minicartSelector).trigger('contentUpdated');
}
if (res.product && res.product.statusText) {
$(self.options.productStatusSelector)
.removeClass('available')
.addClass('unavailable')
.find('span')
.html(res.product.statusText);
}
/*To hide loader on mini-cart*/
setTimeout(function() {
$(".loading-mask").hide();
}, 3000);
/*******************************/
self.enableAddToCartButton(form);
}
I have used setTimeout() function to stop loader after mini-cart count increament.
Best Answer
There are two Methods of updating the minicart
Method 1: Using sections.xml
Create sections.xml file under
app/code/Vendor/Module/etc/frontend
directoryMethod 2: Using customerData dependency in the script tag