Skip to content

Update PostHog import to use React hook #7135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 23, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 30 additions & 26 deletions apps/dashboard/src/hooks/analytics/useTrack.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -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],
);
}
Loading