From 12f25d8bfc2555e5adaaa53eaed0fc66f72ec67b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Berg=C3=A9?= Date: Tue, 7 Jan 2025 15:18:05 +0100 Subject: [PATCH] Fix error from visitor id not set (#2678) --- .../components/Insights/InsightsProvider.tsx | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/packages/gitbook/src/components/Insights/InsightsProvider.tsx b/packages/gitbook/src/components/Insights/InsightsProvider.tsx index e28262dc0..b2b7f219c 100644 --- a/packages/gitbook/src/components/Insights/InsightsProvider.tsx +++ b/packages/gitbook/src/components/Insights/InsightsProvider.tsx @@ -86,15 +86,6 @@ export function InsightsProvider(props: InsightsProviderProps) { | undefined; }>({}); - /** - * Get the visitor ID and store it in a ref. - */ - React.useEffect(() => { - getVisitorId().then((visitorId) => { - visitorIdRef.current = visitorId; - }); - }, []); - /** * Synchronously flush all the pending events. */ @@ -194,13 +185,19 @@ export function InsightsProvider(props: InsightsProviderProps) { }, ); - // When the page is unloaded, flush all events + /** + * Get the visitor ID and store it in a ref. + */ React.useEffect(() => { - window.addEventListener('beforeunload', flushEventsSync); + getVisitorId().then((visitorId) => { + visitorIdRef.current = visitorId; + // When the page is unloaded, flush all events, but only if the visitor ID is set + window.addEventListener('beforeunload', flushEventsSync); + }); return () => { window.removeEventListener('beforeunload', flushEventsSync); }; - }, [flushEventsSync]); + }, []); return (