Categories


Archives


Recent Posts


Categories


Refresh Shipping Rates for the Magento 2 Checkout Application

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

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/

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 3rd February 2017

email hidden; JavaScript is required