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.

  • Also tried using require js but still same. – Narendra Vyas Sep 19 '19 at 11:59
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

| improve this answer | |
  • This solution is exactly the same as your (and mine) not working solution. – TheKitMurkit Nov 23 '19 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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