#StackBounty: #magento2 #ajax #knockout Magento 2 Knockout variable from response in controller via ajax

Bounty: 50

Assume I’ve got something like this

<div class="greet welcome" data-bind="scope: 'customer'">
    <!-- ko if: blockIsLoggedIn == '1'  -->
    <span data-bind="text: new String('<?= $block->escapeHtml(__('According to the block logic you are currently logged In')) ?>')"></span>
    <!-- /ko -->
    <!-- ko ifnot: blockIsLoggedIn == '1'  -->
    <span data-bind="text: new String('<?= $block->escapeHtml(__('as according to the block logic you are not currently logged in')) ?>')"></span>
    <!-- /ko -->
</div>
<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "customer": {
                    "component": "Magento_Customer/js/view/customer",
                    "blockIsLoggedIn": "<?= $block->escapeJs($block->isCustomerLoggedIn()); ?>"
                }
            }
        }
    }
}
</script>

And my block logic looks a bit like this

    /**
     * Check is Customer Logged In
     * @return int
     */
    public function isCustomerLoggedIn()
    {
        $isLoggedIn = $this->customerContext->getValue(MagentoCustomerModelContext::CONTEXT_AUTH);
        return (bool) $isLoggedIn ? 1 : 0;
    }

The trouble is the blockIsLoggedIn value is cached in FPC on page load. Which means you can’t reliably use this approach.

Is it possible to convert this so this variable comes from an ajax lookup on a controller instead?

I’m aware of other ways in which to check whether you are logged in. This is just an example. I’ve had similar scenarios recently and I end up just using jQuery. When I use jQuery I feel like I’m reinventing the wheel.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.