How to select shipping address and trigger shipping rates to update on checkout in Magento 2

  • Post author:
  • Post category:Magento 2

To select shipping address on checkout in Magento 2 you need to do it by calling select-shipping-address action. It will set shipping address to quote. You can do it by defining following component:

First we need to understand what shipping address we want to select. After that we go through all addresses in addressList and call selectShippingAddressAction. This sets our shipping address to the quote. Then we call checkoutData.setSelectedShippingAddress method. That sets our address to the localStorage checkout-data.

Shipping rates are recalculated automatically. It happens because quote.shippingAddress has a subscription in Magento_Checkout/js/model/shipping-rate-service.js. But your shipping address should be set to quote first!!!

To trigger shipping rates to update on checkout you can define Magento_Checkout/js/model/shipping-rate-service dependency to trigger Magento_Checkout/js/model/shipping-rate-processor/new-address.js::getRates method directly.

You can define shipping-rate-service.js in dependencies for it to trigger getRates method. Otherwise getRates method can be called before our needed shipping address is set to quote. Thus without this dependency our shipping rates won’t be estimated and there will be no AJAX request to estimate-shipping-methods.