I'm trying to set ecommerce events on our web-site with GTM. And I'm trying to make custom value with custom JavaScript but it continuously shows undefined
First, I found data script on our website
<script id="__NEXT_DATA__" type="application/json">
And I write custom javascript code like below
function() {
var productInfo = [{
'id':window.__NEXT_DATA__.props.pageProps.program.products[0].id,
'name':window.__NEXT_DATA__.props.pageProps.program.products[0].name,
'price':window.__NEXT_DATA__.props.pageProps.program.products[0].price,
'category':'exhibition'
}];
return productInfo;
}
Our website is developed with next.js, is it impossible to use script data(?) in custom JavaScript?
As far as I understand, __NEXT_DATA__
is loaded asynchronously. Depends on how you setup GTM. It is possible you are running into a race condition where GTM script runs your custom JavaScript function while Next.js is loading the data.
I think a better approach will be:
useEffect
hook.