Magento2: How to refresh the shipping method using JS?

get shipping rates using JS in magento 2 - sb dev blog

Let’s refresh the shipping method using JS. We have restored the total section in https://sbdevblog.com/magento-2-how-to-update-the-total-using-js/

Very often, we need to update the shipping method in the cart and checkout page using JS. For example, on applying a custom discount or rule programmatically on the cart page or any other operation using Ajax.

In such a scenario, we must fetch updated rates for the shipping method to get the correct order total as well as the shipping cost.

To achieve this, we need to inject Magento_Checkout/js/model/quote to get the shipping address, Apart from Quote, we need to inject Magento_Checkout/js/model/shipping-rate-registry.

We will invalidate the key and the cache key of the shipping address, which is stored in the shipping rate registry.

We need to add the line mentioned below to get the shipping address from the quote.

let shippingAddress = quote.shippingAddress();

Then, we need to update the lines mentioned below to invalidate the key and the cache key for the shipping address in the shipping rate registry.

shippingRateRegistry.set(shippingAddress.getKey(), null);
shippingRateRegistry.set(shippingAddress.getCacheKey(), null);

The above lines will clear the cache stored in the shipping rate registry. Finally, we need to call the shippingAddress function of the quote object with the parameter of the shipping address.

Let’s look at the code.

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

That’s it. This is a very simple and easy-to-trigger shipping method with rates at checkout as well as in the cart.

Thank you for reading the article. Magento 2: How to refresh the shipping method using JS?

I hope you like the article. Please subscribe and share. Use the comment box for your suggestions.

Check out the article https://sbdevblog.com/magento-2-how-to-update-mini-cart/ to update the mini cart.

Check out the Git Repository

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 🙂

Leave a Reply

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