From c1db799c333567ee7ff111961570a863af359564 Mon Sep 17 00:00:00 2001 From: Arvid Norlin Date: Fri, 8 Mar 2024 11:36:44 +0100 Subject: [PATCH] fix: improve Tracking useEffect --- components/Current/Tracking.tsx | 65 ++++++++++++++++----------------- 1 file changed, 32 insertions(+), 33 deletions(-) diff --git a/components/Current/Tracking.tsx b/components/Current/Tracking.tsx index 443e81490..b54d480e9 100644 --- a/components/Current/Tracking.tsx +++ b/components/Current/Tracking.tsx @@ -64,7 +64,28 @@ function createPageObject(trackingData: TrackingData) { export default function Tracking({ pageData }: TrackingProps) { const pathName = usePathname() const queryString = useSearchParams().toString() - const [consentCookie, setConsentCookie] = useState(null) + + function CookiebotCallbackOnAccept() { + const cookie = window._satellite.cookie.get("CookieConsent") + + if (window.Cookiebot?.changed && window.adobe) { + if (cookie?.includes("statistics:true")) { + window.adobe.optIn.approve(window.adobe.OptInCategories.ANALYTICS, true) + } else { + window.adobe.optIn.deny(window.adobe.OptInCategories.ANALYTICS, true) + } + window.adobe.optIn.complete() + console.warn("window.load event explicitly dispatched.") + window.dispatchEvent(new Event("load")) + } + } + + function CookebotCallbackOnDecline() { + if (window.Cookiebot?.changed && window.adobe) { + window.adobe.optIn.deny(window.adobe.OptInCategories.ANALYTICS, true) + } + } + useEffect(() => { if (window.datalayer) { const trackingData = { ...pageData, pathName, queryString } @@ -76,39 +97,17 @@ export default function Tracking({ pageData }: TrackingProps) { useEffect(() => { // handle consent - window.addEventListener( - "CookiebotOnAccept", - function CookiebotCallback_OnAccept(e) { - const cookie = window._satellite.cookie.get("CookieConsent") - setConsentCookie(cookie) + window.addEventListener("CookiebotOnAccept", CookiebotCallbackOnAccept) + window.addEventListener("CookiebotOnDecline", CookebotCallbackOnDecline) - if (window.Cookiebot?.changed && window.adobe) { - if (cookie?.includes("statistics:true")) { - window.adobe.optIn.approve( - window.adobe.OptInCategories.ANALYTICS, - true - ) - } else { - window.adobe.optIn.deny( - window.adobe.OptInCategories.ANALYTICS, - true - ) - } - window.adobe.optIn.complete() - window.dispatchEvent(new Event("load")) - } - } - ) - - window.addEventListener( - "CookiebotOnDecline", - function CookebotCallback_OnDecline() { - if (window.Cookiebot?.changed && window.adobe) { - window.adobe.optIn.deny(window.adobe.OptInCategories.ANALYTICS, true) - } - } - ) - }, [consentCookie]) + return () => { + window.removeEventListener("CookiebotOnAccept", CookiebotCallbackOnAccept) + window.removeEventListener( + "CookiebotOnDecline", + CookebotCallbackOnDecline + ) + } + }, []) return null }