How to Refresh Shipping Rates on Checkout Using JS in Magento 2

E-commerce store owners employ different shipping tactics to maximize the profits and hence charge shipping rates based on the location, customer group, etc.

Now, for example, a customer is at the checkout step with some items in the cart to be delivered at a particular location. But if he changes the location of delivery during the checkout, the shipping rates applied for that order also change.

However, if the entire page is reloaded and if he has to go through the checkout again, it contributes to the bad user experience. In this situation, he may abandon the cart also.

In order to avoid it, implement the below solution to refresh shipping rates on checkout using JS in Magento 2.

Method to refresh shipping rates on checkout using JS in Magento 2:

requirejs([
    'Magento_Checkout/js/model/quote',
    'Magento_Checkout/js/model/shipping-rate-registry'
], function(mainQuote, rateReg){
    
    var address = mainQuote.shippingAddress();
    rateReg.set(address.getKey(), null);
    rateReg.set(address.getCacheKey(), null);
    mainQuote.shippingAddress(address);
});

That’s it.

Please share the post with the Magento community via social media.

Thank you.

Jignesh Parmar

Article by

Jignesh Parmar

An expert in his field, Jignesh is the team leader at Meetanshi and a certified Magento developer. His passion for Magento has inspired others in the team too. Apart from work, he is a cricket lover.