11import { flatten } from "flat" ;
2- import posthog from "posthog-js" ;
2+ import { usePostHog } from "posthog-js/react " ;
33import { useCallback } from "react" ;
44
55export type TrackingParams = {
@@ -11,31 +11,35 @@ export type TrackingParams = {
1111} ;
1212
1313export 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