My function (getPageTypeFromDataLayer) is being called multiple times and I think it would be best to store it as a variable and then reference the variable but not sure how to set it up. Can anyone help?
Code:
export const getPageTypeFromDataLayer = function () {
const pageTypeObj = window?.dataLayer?.filter((data) => data.pageType)[0];
if (pageTypeObj) {
return pageTypeObj.pageType;
}
return "unknown";
};
In another section of the code, I reference the function in multiple pages where the data from dataLayer is being pulled. I would like to reference it as a variable instead since it's being called multiple times. Can someone help me to do this?
I think you should just be able to do:
The returned value can be stored like this:
const value = getPageFromDataLayer().You can call the function in the same file with
getPageTypeFromDataLayer()and also call it in other files by importing it withimport { getPageTypeFromDataLayer } from './your-file.js'.Make sure to add
"type": "module"to yourpackage.json.