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], + ); }