react-gtm-hook
react-gtm-hook copied to clipboard
How to clean dataLayer when page changes on Next.js ? Avoid persistance of data in dataLayer
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
- So I go to my index then click on my button
- 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 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
Awesome! Thank you! 🥳
Closing as resolved 😄