A useful code snippet that came out of a discussion on the Patreon slack today.
requirejs([
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/shipping-rate-registry'
], function(quote, rateRegistry){
//get address from quote observable
var address = quote.shippingAddress();
//changes the object so observable sees it as changed
address.trigger_reload = new Date().getTime();
//create rate registry cache
//the two calls are required
//because Magento caches things
//differently for new and existing
//customers (a FFS moment)
rateRegistry.set(address.getKey(), null);
rateRegistry.set(address.getCacheKey(), null);
//with rates cleared, the observable listeners should
//update everything when the rates are updated
quote.shippingAddress(address);
});
The program, (which could be (and should be) easily ported into a define
module) will trigger an update of the Shipping Method section of the Magento 2 Checkout. At least, per today’s Patreon conversation, it will on a stock Magento system.
We discussed some of the underlying code here in a previous quickie. High level, this works because the UI elements are linked to the shippingAddress
observable. Update the shippingAddress
observable, and the Magento UI updates, including a re-fetching of the rates.
We need the following code
rateRegistry.set(address.getKey(), null);
rateRegistry.set(address.getCacheKey(), null);
because Magento will cache (in memory) the rates to avoid refetching them endlessly via ajax every time a user types into the shipping address form, and updating the address doesn’t refresh the cache key(s). The two calls are needed because Magento 2 does that caching differently for the logged in user flow vs. the logged out user flow. If you’re interested in seeing where this caching happens, take a look at the files in
vendor/magento/module-checkout/view/frontend/web/js/model/shipping-rate-processor/