From 561650d6f9cb39b3139bd7138b43196be473c843 Mon Sep 17 00:00:00 2001 From: Riya Amemiya Date: Sat, 21 Sep 2024 23:30:40 +0900 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(analytics):=20prevent=20mult?= =?UTF-8?q?iple=20GTM=20initializations=20(#4174)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(types): Add global window interface for Google Tag Manager * refactor(Chat/Footer): Move GTM initialization to useEffect for better lifecycle management * fix(hooks): add useEffect to initialize TagManager conditionally --- client/src/common/types.ts | 6 ++++++ client/src/components/Chat/Footer.tsx | 18 ++++++++++-------- client/src/hooks/Config/useAppStartup.ts | 14 ++++++++------ 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/client/src/common/types.ts b/client/src/common/types.ts index b969346e70..461dfcbe48 100644 --- a/client/src/common/types.ts +++ b/client/src/common/types.ts @@ -540,3 +540,9 @@ export type TVectorStore = { }; export type TThread = { id: string; createdAt: string }; + +declare global { + interface Window { + google_tag_manager?: unknown; + } +} \ No newline at end of file diff --git a/client/src/components/Chat/Footer.tsx b/client/src/components/Chat/Footer.tsx index d4b04698e2..b534aee018 100644 --- a/client/src/components/Chat/Footer.tsx +++ b/client/src/components/Chat/Footer.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useEffect } from 'react'; import ReactMarkdown from 'react-markdown'; import TagManager from 'react-gtm-module'; import { Constants } from 'librechat-data-provider'; @@ -34,13 +34,6 @@ export default function Footer({ className }: { className?: string }) { ); - if (config?.analyticsGtmId != null) { - const tagManagerArgs = { - gtmId: config.analyticsGtmId, - }; - TagManager.initialize(tagManagerArgs); - } - const mainContentParts = ( typeof config?.customFooter === 'string' ? config.customFooter @@ -50,6 +43,15 @@ export default function Footer({ className }: { className?: string }) { localize('com_ui_latest_footer') ).split('|'); + useEffect(() => { + if (config?.analyticsGtmId != null && typeof window.google_tag_manager === 'undefined') { + const tagManagerArgs = { + gtmId: config.analyticsGtmId, + }; + TagManager.initialize(tagManagerArgs); + } + }, [config?.analyticsGtmId]); + const mainContentRender = mainContentParts.map((text, index) => ( { + if (startupConfig?.analyticsGtmId != null && typeof window.google_tag_manager === 'undefined') { + const tagManagerArgs = { + gtmId: startupConfig.analyticsGtmId, + }; + TagManager.initialize(tagManagerArgs); + } + }, [startupConfig?.analyticsGtmId]); }