Skip to content

Commit 005acce

Browse files
committed
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.
1 parent cde2dd9 commit 005acce

File tree

1 file changed

+30
-26
lines changed

1 file changed

+30
-26
lines changed
Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { flatten } from "flat";
2-
import posthog from "posthog-js";
2+
import { usePostHog } from "posthog-js/react";
33
import { useCallback } from "react";
44

55
export type TrackingParams = {
@@ -11,31 +11,35 @@ export type TrackingParams = {
1111
};
1212

1313
export function useTrack() {
14-
return useCallback((trackingData: TrackingParams) => {
15-
const { category, action, label, ...restData } = trackingData;
16-
const catActLab = label
17-
? `${category}.${action}.${label}`
18-
: `${category}.${action}`;
19-
if (process.env.NODE_ENV !== "production") {
20-
console.debug(`[PH.capture]:${catActLab}`, restData);
21-
}
14+
const posthog = usePostHog();
15+
return useCallback(
16+
(trackingData: TrackingParams) => {
17+
const { category, action, label, ...restData } = trackingData;
18+
const catActLab = label
19+
? `${category}.${action}.${label}`
20+
: `${category}.${action}`;
21+
if (process.env.NODE_ENV !== "production") {
22+
console.debug(`[PH.capture]:${catActLab}`, restData);
23+
}
2224

23-
const restDataSafe = Object.fromEntries(
24-
Object.entries(restData).map(([key, value]) => {
25-
if (value instanceof Error) {
26-
return [
27-
key,
28-
{ message: value.message, stack: value.stack?.toString() },
29-
];
30-
}
31-
return [key, value];
32-
}),
33-
);
25+
const restDataSafe = Object.fromEntries(
26+
Object.entries(restData).map(([key, value]) => {
27+
if (value instanceof Error) {
28+
return [
29+
key,
30+
{ message: value.message, stack: value.stack?.toString() },
31+
];
32+
}
33+
return [key, value];
34+
}),
35+
);
3436

35-
try {
36-
posthog.capture(catActLab, flatten(restDataSafe));
37-
} catch {
38-
// ignore - we just don't want to trigger an error in the app if posthog fails
39-
}
40-
}, []);
37+
try {
38+
posthog?.capture(catActLab, flatten(restDataSafe));
39+
} catch {
40+
// ignore - we just don't want to trigger an error in the app if posthog fails
41+
}
42+
},
43+
[posthog],
44+
);
4145
}

0 commit comments

Comments
 (0)