How to Manage CustomerData Entity in Magento 2

How to Manage CustomerData Entity in Magento 2

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.

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:

This way you may control the update of Local Storage data in the user’s browser and update user’s data if necessary.



Post a new comment

top