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

How to clean dataLayer when page changes on Next.js ? Avoid persistance of data in dataLayer #54

Closed Steffi3rd closed 1 year ago

Steffi3rd commented 2 years ago

Hello,

I use this repo for few weeks now and it works fine and very cool, thank you for that. I just would ask a question about if it's possible to reset dataLayer when page changes.

For example :

Code

I have this in my _app.tsx

const gtmParams = {
    id: process.env.NEXT_PUBLIC_GOOGLE_GTM_ID as string,
    dataLayerName: "dataLayer",
    dataLayer: {},
};

<GTMProvider state={gtmParams}>
    <Component {...pageProps} />
</GTMProvider>

And this, in my index.tsx

  const sendDataToGTM = useGTMDispatch()
  const handleClick = () => sendDataToGTM({ 
      ecommerce: {
        add: {
          products: [
            {
              name: space.label,
            },
          ],
        },
      },
})

  <button onClick={handleClick}>My Awesome Button</button>

And this, in my contact.tsx

  const sendDataToGTM = useGTMDispatch()
  const handleClick = () => sendDataToGTM({ 
      ecommerce: {
        detail: {
          products: [
            {
              id: space.id,
            },
          ],
        },
      },
})

  <button onClick={handleClick}>My Awesome Button</button>

Workflow

  1. So I go to my index then click on my button
  2. Then go the my contact page then click on my button

Result

The result of that is

      ecommerce: {
        add: {
          products: [
            {
              name: "Space 1",
            },
          ],
        },
      },
      ecommerce: {
        add: {
          products: [
            {
              name: "Space 1",
            },
          ],
        },
        detail: {
          products: [
            {
              id: "1',
            },
          ],
        },
      },

instead :

    ecommerce: {
        detail: {
          products: [
            {
              id: "1',
            },
          ],
        },
      },

I would like to not merge previous state with the new one.

Is there a way to do that please ?

precious-void commented 2 years ago

@Steffi3rd the issue is not related to this lib. Here is a section on how to prevent objects merging from GA UA documentation: https://developers.google.com/analytics/devguides/collection/ua/gtm/enhanced-ecommerce#clear-ecommerce

Steffi3rd commented 2 years ago

Awesome! Thank you! 🥳

elgorditosalsero commented 1 year ago

Closing as resolved 😄