Fix Magento JavaScript Component Initialization Before PHTML Script – Magento 2

magento2requirejs

I'm trying to call a Magento Javascript Component in my phtml page to get the customer data saved in session.

I'm having an issue in that the customerdata constructor gets loaded after my script and I can't figure out how to get my script to run after.

This is the customer-data.js file that needs to get loaded before my script

'Magento_Customer/js/customer-data': function (settings) {
            options = settings;
            invalidateCacheBySessionTimeOut(settings);
            invalidateCacheByCloseCookieSession();
            customerData.init();
 }

Here is how I'm trying to call it

require([
    'jquery',
    'Magento_Customer/js/customer-data',
    'domReady!',
    'mage/loader'
], function (jQuery,customerData) {
    //<![CDATA[
    jQuery(document).ready(function() {

        var data = customerData.get('mysession-data');


    });
});

My code works when the customerdata gets initialized but it's not always getting initialized first.

Is there anyway to configure this to get the customerdata to initialize and then I can call my session data?

Best Answer

You can try to use RequireJs mixins in order to hook the core function.

var config = {
    'config':{
        'mixins': {
            'Magento_Customer/js/customer-data': {
                'Vendor_Module/hook.js':true
            }
        }
    }
}; 

Alan Storm described it here : http://alanstorm.com/the-curious-case-of-magento-2-mixins/

You can try to use shim option with requirejs as explain here :

Requirejs shim option not working

Related Topic