2

I need to call some js in a phtml file only on product details page. I need to check some customer attribute there and show a popup accordingly.

The issue I am facing is that somehow I am unable to get details from customerData on page load and it seems as if my js is loaded before the page loads.

I added setTimeout and after that everything works perfectly.

catalog_product_view.xml

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="before.body.end">
        <block name="trail.user.info" template="Test_TrialuserRestriction::trialuserinfo.phtml" />
    </referenceContainer>
</body>

trialuserinfo.phtml

<script type="text/javascript">
require(['jquery', 'domReady!', 'Magento_Customer/js/customer-data'], function($, domready, customerData){
    'use strict';

     // Uncommenting this not works for me
    // var customer = customerData.get('customer');
    // console.log(customer().firstname);

    //This works for me when I add timeout
    setTimeout(function(){
        var customer = customerData.get('customer');
        console.log(customer().firstname);
    }, 5000);

})

[Edit]

Also tried including the js file using require-config.js but still same.

Any help please.

Narendra Vyas
  • 1,327
  • 10
  • 28

1 Answers1

1

If anyone is in need of a better and working solution, here you go.

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

http://slides.yireo.com/yireo/m2_private_content#1

Narendra Vyas
  • 1,327
  • 10
  • 28