From ec06ed9557dcb56ab534dcac3f44dfb6f4e85fad Mon Sep 17 00:00:00 2001 From: Thijs Daniels Date: Fri, 25 Oct 2024 17:24:10 +0200 Subject: [PATCH] feat(react-tracking): prepare dataLayer --- .changeset/tender-rats-jam.md | 5 +++++ packages/react-tracking/utilities/createGtmTracker.ts | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 .changeset/tender-rats-jam.md diff --git a/.changeset/tender-rats-jam.md b/.changeset/tender-rats-jam.md new file mode 100644 index 00000000..59431a85 --- /dev/null +++ b/.changeset/tender-rats-jam.md @@ -0,0 +1,5 @@ +--- +"@codedazur/react-tracking": patch +--- + +The dataLayer is now prepared in case the script is not yet loaded. diff --git a/packages/react-tracking/utilities/createGtmTracker.ts b/packages/react-tracking/utilities/createGtmTracker.ts index d76338bb..c8e923d4 100644 --- a/packages/react-tracking/utilities/createGtmTracker.ts +++ b/packages/react-tracking/utilities/createGtmTracker.ts @@ -10,7 +10,9 @@ export function createGtmTracker({ prefix, }: { prefix?: string } = {}): Tracker { return function gtmTracker({ type, ...event }) { - window.dataLayer?.push({ + window.dataLayer = window.dataLayer || []; + + window.dataLayer.push({ event: [prefix, type].filter(Boolean).join("."), ...event, });