elgorditosalsero / react-gtm-hook

Easily manage the Google Tag Manager via Hook
https://elgorditosalsero-react-gtm-hook.netlify.app/
MIT License
220 stars 28 forks source link

Question: how to send data on initialization? #13

Closed brahimmouhamou closed 3 years ago

brahimmouhamou commented 3 years ago

Hi there,

I'm creating a custom consent modal that saves consents in a cookie.

So everything works fine when I'm using sendDataToGTM in a callback function. But on a refresh of the page I would like to immediately send the needed triggers (saved in a cookie) to GTM. When using sendDataToGTM in a useEffect it gives me the following error:

TypeError: Cannot read property 'push' of undefined

How should I set the initial dataLayer object to push events on init?

I tried passing a dataLayer array but that didn't work:

init({ id: "GTM-XXX", dataLayer: [{ event: "my-event"} ] })

Thanks in advance!

elgorditosalsero commented 3 years ago

Hi @brahimmouhamou, thx for opening the Issue.

Probably you get that error because is trying to push before the GTM is fully loaded.

If I understood right, you need to send some consent to the GTM to do operations based on that (I'm thinking about consent like GDPR).

I think a good solution is passing them on init if those are available in the cookie, without firing an event.

So you can do something like: init({ id: "GTM-XXX", dataLayer: { consent1, consent2 }}) where consents are calculated like: const consent1 = cookieFn(cookieName) || 'default'

And then, read them into the GTM on load.

Btw, I'll see how, and if is possible, implement the push of an event after the init.

Hope those tips are useful right now 😄

brahimmouhamou commented 3 years ago

Hi @elgorditosalsero, thanks for fast response!

I was unaware that I could map the dataLayer object to GTM variables and create a trigger that can listen to a pageview with certain GTM variables. This solves my problem!

Much appreciated!