react-gtm
react-gtm copied to clipboard
How to avoid TagManager.initialize() running many times
Hello.
In my React component, I have to get gtm-ID from another data which change many time. Each time this data changes, my component render. And each time component renders, function TagManager.initialize runs again, this create duplicate gtm scripts (as attached).
My code:
useEffect(() => {
if (data.gtm_id){
TagManager.initialize({
gtmId: data.gtm_id,
});
}
}, [data.gtm_id])
Could you please advise me how to avoid function TagManager.initialize() to run if it already run?
Thank you.
+1
I have the same issue
@seandelaney have you found solution? Currently I have to check if the above script tag already existed, will do nothing. But I think this solution is not safe because actually I don't know what this library does in the background.
@vanminhquangtri No solution yet
We have the same issue. Any hacks on this?
I'd recommend to just keep track of gtm_id
and check if it was previously used before initialising it again
There is any solution for this bug?
@vanminhquangtri Based on what you wrote, the initialize
function will be called again if data.gtm_id
changes. As written, because you have passed data.gtm_id
as a dependency on useEffect
, it will be called any time it is modified. A potential solution here would be the following:
useEffect(() => {
if (data.gtm_id){
TagManager.initialize({
gtmId: data.gtm_id,
});
}
}, []) // Remove data.gtm_id from the dependencies
+1 on this.
A callback function with onLoad
should be helpful. Or the implementation of useScript hook inside the react-gtm module would be helpful.