1

This is the usual way to get customerData on frontend.

define([
    'uiComponent',
    'Magento_Customer/js/customer-data'
], function (Component, customerData) {
    'use strict';

    return Component.extend({
        initialize: function () {
            this._super();

            this.firstname = customerData.get('customer')().firstname;
        }
    });
});

Problem: oth the first load of the page, when mage-cache-storage in local storage is cleared, customerData.get('customer')().firstname returns undefined. And at this moment, request to server is sent, but js doesn't wait for the response, and the variable is undefined.

I guess it has to be done asynchronously. But how to do it correctly?

I have found these stack questions, but the solutions are the same as mine. Am I missing something?

  1. How to call customerData js in phtml on a specific page after page load

  2. Magento2 RequireJS CustomerData is empty at page load, but populated once page finishes loading?

  3. GitHub: Magento_Customer/js/customer-data empty on the first page after login

Edit 1:

subscribe works, but it is executed after knockout.

var customer = customerData.get('customer');
customer.subscribe(function (customer) {
    console.log(customer.firstname);
}, this);

1 Answer 1

0

This was the answer. I'm not sure what I was expecting. I wanted the process in ko viewmodel to wait for the data to load, but apparently it happens somewhere else under the hood.

https://magento.stackexchange.com/a/210888/52739

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.