9

How do I check if customer is logged in or not in knockout template?

my template

<!-- ko if: customer().firstname -->

<!-- /ko -->

my js

 define(
    [
        'ko',
        'jquery',
        'Magento_Ui/js/form/element/abstract',
        'mage/url',
        'Magento_Customer/js/customer-data',
        'mage/translate'
    ],
    function (Component,storage,ko,jquery,Abstract, url, customerData, $t) {
        'use strict';

        return Component.extend({
            message: function() {
            loggedMessage : $t('Welcome, %1!')
            },
            htmlLoggedMessage: ko.observable(),
            isLoggedIn: ko.observable(),
            customer: ko.observable({}),
            initialize: function() {
                this._super();
                if(this.isCustomerLogged != 0) {
                    this.isLoggedIn(true);
                }
                this.checkCustomerLocalStorage();
            },
            /**
             * Check customer localstorage
             */
            checkCustomerLocalStorage: function () {
                var self = this;
                var time = setInterval(function () {
                    self.customer = customerData.get('customer');
                    if (localStorage["mage-cache-storage"] != '{}') {
                        clearInterval(time);
                    }
                    if (self.customer().fullname) {
                        var name = self.customer().fullname;
                        var message = self.message.loggedMessage.replace('%1', name);
                        self.htmlLoggedMessage(message);
                    }
                }, 1000);
            }
        });
    }
);

I followed this link but its still entering in to if condition:

How to check if customer is logged in or not in magento 2?

sv3n
  • 11,657
  • 7
  • 40
  • 73
Nagendra Kodi
  • 1,324
  • 1
  • 17
  • 39

4 Answers4

15

You need to pass dependency of customer object, 'Magento_Customer/js/model/customer',

define(
[
    'ko',
    'jquery',   
    'Magento_Customer/js/model/customer',
    'mage/translate'
],
function (ko,jquery, customer,$t) {
    'use strict';
    return Component.extend({        
        isCustomerLoggedIn: customer.isLoggedIn, /*return  boolean true/false */
        initialize: function() {
            this._super();
            /* check using below method */
            var isLoggedIn = this.isCustomerLoggedIn();
        }
    });
}

Now you can check it using customer.isLoggedIn() returns boolean value.

define(
[
    'ko',
    'jquery',
    'Magento_Ui/js/form/element/abstract',
    'mage/url',
    'Magento_Customer/js/customer-data',    
    'Magento_Customer/js/model/customer',
    'mage/translate'
],
function (Component,storage,ko,jquery,Abstract, url, customerData, customer,$t) {
    'use strict';

    return Component.extend({
        message: function() {
        loggedMessage : $t('Welcome, %1!')
        },
        htmlLoggedMessage: ko.observable(),
        isLoggedIn: ko.observable(),
        isCustomerLoggedIn: customer.isLoggedIn,
        customer: ko.observable({}),
        initialize: function() {
            this._super();
            if(this.isCustomerLoggedIn()) {
                this.isLoggedIn(true);
            }
            this.checkCustomerLocalStorage();
        },
        /**
         * Check customer localstorage
         */
        checkCustomerLocalStorage: function () {
            var self = this;
            var time = setInterval(function () {
                self.customer = customerData.get('customer');
                if (localStorage["mage-cache-storage"] != '{}') {
                    clearInterval(time);
                }
                if (self.customer().fullname) {
                    var name = self.customer().fullname;
                    var message = self.message.loggedMessage.replace('%1', name);
                    self.htmlLoggedMessage(message);
                }
            }, 1000);
        }
    });
}
Rakesh Jesadiya
  • 42,221
  • 18
  • 132
  • 183
  • Welcome @nagendra Glad to know you have useful. – Rakesh Jesadiya Nov 30 '17 at 13:38
  • 5
    from what I can tell customer.isLoggedIn() only works on the checkout as it checks the window object in vendor/magento/module-customer/view/frontend/web/js/model/customer.js. Your function checkCustomerLocalStorage is what works on all other pages and it could be simplified to use something like customerData.get('customer').fullname – Holly Aug 02 '18 at 17:40
  • Also, I don't see the need for the setInterval function and checking localStorage, can you remember why you used them? Thanks all the same, the answer was helpful :) – Holly Aug 02 '18 at 17:42
  • This worked for me: customerData.get('customer')().fullname, note additional () parentheses to call get(), because it is a function – TheKitMurkit Apr 26 '19 at 08:28
  • @RakeshJesadiya, could you please have a look at my post on the similar issue? I'm not sure how to implement the solution given by you. Here is my post. https://magento.stackexchange.com/questions/358323/magento-2-4-2-unable-to-process-binding-ifnot-functionreturn-customer-fu – CodeForGood Jul 28 '22 at 05:23
1

It is quite simple, inside Magento_Customer/js/view/customer class there is a method firstname and we can use it to check if a customer is logged in or not.

<!-- ko if: customer().firstname  -->
    <?= __('Out') ?>
<!-- /ko -->
<!-- ko ifnot: customer().firstname  -->
    <?= __('In') ?>
<!-- /ko -->
<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "customer": {
                        "component": "Magento_Customer/js/view/customer"
                    }
                }
            }
        }
    }
</script>
Andrei
  • 237
  • 2
  • 5
  • 1
    For Magento2.4 at least, do not forget to add data-bind="scope: 'customer'" to the parent element where you perform the checks. – Victor F Apr 29 '22 at 07:53
  • Not really going to work as you think. knockout is js. At best you are going to have a flash of content. You would build this in an html template and load it via knockout. Otherwise for a phtml file you would do this via viewmodel and check the customer's session. Cache is built by customer group for this reason. – user3685048 Jan 02 '23 at 19:59
0

Here is another example(customer.isLoggedIn with ko.observable()):-

define([
    'ko',
    'jquery',
    'uiComponent',
    'Magento_Customer/js/model/customer',
], function (ko, $, Component, customer) {
    'use strict';

    var checkoutConfig = window.checkoutConfig,
        ConfigIsEnabled = checkoutConfig ? checkoutConfig.AppIsEnabled : {};

    return Component.extend({
        defaults: {
            template: 'Magento_CustomModule/checkout/app-agreements'
        },
        isVisible: ko.observable(),
        isCustomerLoggedIn: customer.isLoggedIn,

        initialize: function () {
            this._super();

            if (!this.isCustomerLoggedIn()) {
                this.isVisible(false);
            } else {
                this.isVisible(ConfigIsEnabled);
            }
        }
    });
});
Nithin Ninan
  • 391
  • 2
  • 8
-1

Just for some extra clarity:

ko.observable(window.isCustomerLoggedIn)

And

customer.isLoggedIn

Mentioned above will only work on checkout, cart, and knockout templates. for everything else you need to use:

    requirejs(['Magento_Customer/js/customer-data'], function (customerData) {
        var firstname = customerData.get('customer')().firstname;
        if (typeof (firstname) === "undefined") {
//Customer is not logged in
else{
// Customer is logged in
}
});