1
1
import { flatten } from "flat" ;
2
- import posthog from "posthog-js" ;
2
+ import { usePostHog } from "posthog-js/react " ;
3
3
import { useCallback } from "react" ;
4
4
5
5
export type TrackingParams = {
@@ -11,31 +11,35 @@ export type TrackingParams = {
11
11
} ;
12
12
13
13
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
+ }
22
24
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
+ ) ;
34
36
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
+ ) ;
41
45
}
0 commit comments