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:
1 2 3 4 5 6 7 8 9 10 |
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); }); |
If you have any doubts regarding the solution, feel free to mention them in the Comments section below. I’d be happy to help.
Please share the post with the Magento community via social media.
Thank you.
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.
14 Comments
Hey man I want to reload shipping rates when street address changed. What exactly i have to do?
Hello,
You may refer to https://meetanshi.com/blog/change-shipping-price-on-address-field-change-in-magento-2-custom-shipping-method/ for the required solution.
Thank You.
Thanks you
Welcome 🙂
Works fine in M2.3 to refresh the shipping method section, but rates are not updated. I’ve used this JS on country dropdown change action.
Hello Nitin,
I’ve used the above solution for the country and state dropdown which works perfectly.
Please check in the default shipping method.
Thanks.
I would like to refresh the shipping quote when city changed. How do this code work for that?
Hello,
You have to place the code at the event of city change.
Thanks.
need i to put this code in js in magento default or in my onestepcheckout module or in my theme? thanks.
Hello,
You can put this code wherever needed.
If it is required in the default file, you can create custom extension and override it for the solution.
Thanks.
hey, where i need to put this line? iam new
Hello Jeff,
Please put this line into your js file where you want to refresh the shipping rate.
Thanks.
Not working on M2.3
Hello Frank,
We have implemented this solution in Magento 2.3.
Why don’t you try this code in one of your JS files. It will work.
Thank you.