To enhance dynamic functionality in Magento 2 that bypasses the full page cache feature, I have written hole punch feature that may help you to see a working example. (see https://bitbucket.org/magstaging/punchhole for more details
step 1: create a model that implements \Magento\Customer\CustomerData\SectionSourceInterface and implement the function getSectionData
class APIData implements SectionSourceInterface
{
public function getSectionData()
{
return [
'result'=> $this->getMyCustomerDynamicData()
];
}
}
step 2: define in a frontend di.xml a section node for the model Magento\Customer\CustomerData\SectionPool
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Customer\CustomerData\SectionPool">
<arguments>
<argument name="sectionSourceMap" xsi:type="array">
<item name="dynamic-data" xsi:type="string">Mbs\PunchHole\CustomerData\DynamicData</item>
</argument>
</arguments>
</type>
</config>
step 3: enable the node to be activated with an action (for instance checkout/cart/add
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
<action name="checkout/cart/add">
<section name="dynamic-data"/>
</action>
</config>
step 4: create a phtml template that will use your node
<script type="text/x-magento-init">
{
"*":{
"Magento_Ui/js/core/app": {
"components": {
"dynamic-data": {
"component":"Mbs_PunchHole/js/jspart"
}
}
}
}
}
</script>
<div data-bind="scope: 'dynamic-data'">
<div data-bind="text: showMyDynamicResult()"></div>
</div>
step 5: create a js file in view/frontend/web/js/jspart.js
define(
[
'uiComponent',
'Magento_Customer/js/customer-data'
],
function (Component, customerData) {
'use strict';
return Component.extend({
data: function () {
const v = customerData.get('dynamic-data');
return v().result || 0;
},
showMyDynamicResult: function () {
return this.data();
}
});
});