I have very little experience with Magento2, but am striking a problem that potentially requires some insight from somebody who does.
I only have front-end access.
I am including the following magento-init
block:
<script type="text/x-magento-init">
{
"*":
{
"Magento_Customer\/js\/customer-data":
{
"sectionLoadUrl": "http:\/\/www.example.com\/customer\/section\/load\/",
"cookieLifeTime": "3600",
"updateSessionUrl": "http:\/\/www.example.com\/customer\/account\/updateSession\/"
}
}
}
</script>
in the body
of my page, which I would expect to populate a sectionLoadUrl
under Magento_Customer/js/customer-data
.
Just before my closing </body>
tag, I include a file which executes the following function:
function highlightWishlistHearts() {
require(['Magento_Customer/js/customer-data'], function(customerData) {
customerData.reload(['wishlist'], false).complete(function(response) {
var customerWishlist = jQuery.parseJSON(response.responseText).wishlist.items;
for (var i = 0, wishlistLength = customerWishlist.length; i < wishlistLength; i++) {
var productURL = customerWishlist[i].product_url;
jQuery('.product-item-actions').each(function() {
if (productURL === jQuery(this).data('product-url')) {
jQuery(this).children('.towishlist.remove').addClass('inwishlist');
}
});
}
});
});
}
The purpose of this function is to add a class to those products on the page that belong to the user's wishlist.
However, this throws a console error, specifying that sectionLoadUrl is undefined
. If I instead call the function from inside a setTimeout
, it executes as I would expect, after the specified timeout of 5s.
I want to avoid using a setTimeout
, so would encourage any ideas around how I can resolve this issue. Is there perhaps a way to force the magento-init
block to be executed when it is defined? Is there perhaps another dependency I could add to my require
block that would force this to wait a sufficient length of time? Is there more that I need to be considering? I have tried including the magento-init
block in the head
of the page, but didn't see any better of a result.
I eventually found that the reload()
function was making a request to http://www.example.com/customer/section/load/?sections=wishlist&update_section_id=false, so I instead performed an AJAX request to this page, and read from the JSON on there. Got rid of the setTimeout
, as was desired.