Magento – How to save shipping address and load it from cookie/local storage in Magento 2

checkoutjavascriptknockoutjsmagento-2.1magento2

How can I save shipping address in cookie/localstorage when user fill it and whenever he/she come back to checkout page it automatically populate the saved data from cookie/localstorage in to corresponding fields – For guest user only.

I have done this in Magento 1 but In magento 2 Most of the checkout page is rendered by knockout js(I have zero knowledge of knockout js), I have no Idea how to proceed.

any help is appreciated

Best Answer

In your JS UI component, you will have to inject Magento_Customer/js/customer-data

Example:

define([
    "jquery",
    "ko",
    "uiComponent",
    "Magento_Customer/js/customer-data"
], function ($, ko, Component, customerData) {
    var self = {
        initialize: function () {
            this._super();

            var checkoutData = customerData.get('checkout-data')();

            checkoutData.shippingAddressFromData = {
                firstname: 'your firstname',
                lastname: 'your lastname',
                company: 'your company',
                street: { 0: 'street line 1', 1: 'street line 2' },
                city: 'your city',
                postcode: 'your postcode',
                region: 'region name',
                region_id: 'region ID of dropdown',
                country_id: 'US',
                fax: '1112223333',
                telephone: '4445556666'
            };

            customerData.set('checkout-data', checkoutData);
        }
    };

    return Component.extend(self);
});

Be sure to the the customer-data.js get to get the data, alter it, and then set it with the set method. Straight setting the data will give a validation error.

Of course you can use that code wherever you like, I just tried to give a basic example of an entire uiComponent in Magento 2, plus the answer local storage questions.

Hope that helps! Cheers!

Related Topic