react-gtm icon indicating copy to clipboard operation
react-gtm copied to clipboard

How to avoid TagManager.initialize() running many times

Open vanminhquangtri opened this issue 2 years ago • 8 comments

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.

image

vanminhquangtri avatar Oct 10 '22 03:10 vanminhquangtri

+1

I have the same issue

seandelaney avatar Oct 12 '22 17:10 seandelaney

@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 avatar Oct 13 '22 01:10 vanminhquangtri

@vanminhquangtri No solution yet

seandelaney avatar Oct 14 '22 09:10 seandelaney

We have the same issue. Any hacks on this?

mouthzipper avatar Nov 28 '22 16:11 mouthzipper

I'd recommend to just keep track of gtm_id and check if it was previously used before initialising it again

drplauska avatar Jan 17 '23 10:01 drplauska

There is any solution for this bug?

Sashaejarque avatar Aug 01 '23 14:08 Sashaejarque

@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

gcko avatar Aug 10 '23 02:08 gcko

+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.

giorgiabosello avatar Jan 15 '24 07:01 giorgiabosello