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

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

Open Steffi3rd opened this issue 2 years ago • 2 comments

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 ?

Steffi3rd avatar Apr 12 '22 14:04 Steffi3rd

@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

precious-void avatar May 05 '22 13:05 precious-void

Awesome! Thank you! 🥳

Steffi3rd avatar May 06 '22 19:05 Steffi3rd

Closing as resolved 😄

elgorditosalsero avatar Apr 28 '23 09:04 elgorditosalsero