From 005acce71481a2e00ecfc33d9c756bca5ae385b1 Mon Sep 17 00:00:00 2001 From: jnsdls Date: Fri, 23 May 2025 04:34:30 +0000 Subject: [PATCH] Update PostHog import to use React hook (#7135) # Update PostHog import to use React hook This PR updates the PostHog implementation in the `useTrack` hook to use the React-specific hook from PostHog instead of the direct import. The changes include: - Replaced the direct import of `posthog` with `usePostHog` from `posthog-js/react` - Added the PostHog instance as a dependency to the `useCallback` hook - Added a null check before calling `posthog.capture()` to handle cases where PostHog might not be initialized These changes ensure proper React integration with PostHog and prevent potential issues with the hook's dependency array. --- .../dashboard/src/hooks/analytics/useTrack.ts | 56 ++++++++++--------- 1 file changed, 30 insertions(+), 26 deletions(-) diff --git a/apps/dashboard/src/hooks/analytics/useTrack.ts b/apps/dashboard/src/hooks/analytics/useTrack.ts index 16eefc5b746..a3fbef23638 100644 --- a/apps/dashboard/src/hooks/analytics/useTrack.ts +++ b/apps/dashboard/src/hooks/analytics/useTrack.ts @@ -1,5 +1,5 @@ import { flatten } from "flat"; -import posthog from "posthog-js"; +import { usePostHog } from "posthog-js/react"; import { useCallback } from "react"; export type TrackingParams = { @@ -11,31 +11,35 @@ export type TrackingParams = { }; export function useTrack() { - return useCallback((trackingData: TrackingParams) => { - const { category, action, label, ...restData } = trackingData; - const catActLab = label - ? `${category}.${action}.${label}` - : `${category}.${action}`; - if (process.env.NODE_ENV !== "production") { - console.debug(`[PH.capture]:${catActLab}`, restData); - } + const posthog = usePostHog(); + return useCallback( + (trackingData: TrackingParams) => { + const { category, action, label, ...restData } = trackingData; + const catActLab = label + ? `${category}.${action}.${label}` + : `${category}.${action}`; + if (process.env.NODE_ENV !== "production") { + console.debug(`[PH.capture]:${catActLab}`, restData); + } - const restDataSafe = Object.fromEntries( - Object.entries(restData).map(([key, value]) => { - if (value instanceof Error) { - return [ - key, - { message: value.message, stack: value.stack?.toString() }, - ]; - } - return [key, value]; - }), - ); + const restDataSafe = Object.fromEntries( + Object.entries(restData).map(([key, value]) => { + if (value instanceof Error) { + return [ + key, + { message: value.message, stack: value.stack?.toString() }, + ]; + } + return [key, value]; + }), + ); - try { - posthog.capture(catActLab, flatten(restDataSafe)); - } catch { - // ignore - we just don't want to trigger an error in the app if posthog fails - } - }, []); + try { + posthog?.capture(catActLab, flatten(restDataSafe)); + } catch { + // ignore - we just don't want to trigger an error in the app if posthog fails + } + }, + [posthog], + ); }