In my previous article I described different ways how you may use CustomerData for your own purposes. It is also possible to control data actuality from the frontend-side by describing the file sections.xml, i.e. we can define specific paths which will update specific sections of customerData upon receiving a request. But this is true only for POST and PUT types of requests. But what would you do if you needed to update some page section without using AJAX or sending any requests? That is why we need to have the possibility to control customerData sections also from the backend-side. For example, you use a system which automatically adds a product to the shopping cart once you load a specific URL. So, at first sight everything looks fine and the system is working perfectly well, however, there is one drawback: once a product is added to the shopping cart but the cart has not been updated yet on the client-side you will have no possibility to access user’s browser local storage. But in Magento 2 there is a way to update data which have been initialized in the backend. You need to use cookies for that. Let’s have a look at the following code in the file:
vendor/magento/module-customer/view/frontend/web/js/customer-data.js
And check the method needReload.
This method is called upon customerData objects initialization that is why it is implemented upon every page load.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
needReload: function () { var cookieSections = $.cookieStorage.get('section_data_ids'), storageVal, name; if (typeof cookieSections != 'object') { return true; } for (name in cookieSections) { if (name !== undefined) { storageVal = storage.get(name); if (typeof storageVal === 'undefined' || typeof storageVal == 'object' && cookieSections[name] > storageVal['data_id'] ) { return true; } } } return false; } |
From the above code it is clear that we take the section_data_ids cookies from the cookie Storage and compare the time of the last data update with the time of recording the section into cookies. So, all we need to do next is to save into the cookies the name of the required section, for example, in the following way:
1 2 3 4 |
$publicMetaData = $this->_cookieMetadataFactory->createPublicCookieMetadata(['path'=>'/']); $cart = []; $cart['cart'] = \time(); $this->_cookieManager->setPublicCookie('section_data_ids', json_encode($cart), $publicMetaData); |
This way you may control the update of Local Storage data in the user’s browser and update user’s data if necessary.