11import ReactGA from "react-ga4" ;
22
3+ declare global {
4+ interface Window {
5+ gtag ?: ( ...args : unknown [ ] ) => void ;
6+ dataLayer ?: unknown [ ] ;
7+ }
8+ }
9+
310export const initGA = ( measurementId : string ) => {
411 ReactGA . initialize ( measurementId ) ;
512} ;
613
714export const logPageView = ( url : string ) => {
15+ if ( localStorage . getItem ( 'userProgram' ) )
16+ {
17+ ReactGA . send ( { hitType : "pageview" , page : url , program : localStorage . getItem ( 'userProgram' ) } ) ;
18+ return ;
19+
20+ }
21+ else
822 ReactGA . send ( { hitType : "pageview" , page : url } ) ;
923} ;
1024
@@ -19,10 +33,40 @@ export const logEvent = ({
1933 label ?: string ;
2034 value ?: number ;
2135} ) => {
22- ReactGA . event ( {
23- action,
24- category,
25- label,
26- value,
27- } ) ;
36+ if ( typeof window === "undefined" ) return ;
37+
38+ const userProgram = localStorage . getItem ( 'userProgram' ) ;
39+
40+ // Build event parameters for GA4
41+ const eventParams : Record < string , string | number > = {
42+ event_category : category ,
43+ } ;
44+
45+ // Add optional fields
46+ if ( label ) {
47+ eventParams . event_label = label ;
48+ }
49+ if ( value !== undefined ) {
50+ eventParams . value = value ;
51+ }
52+
53+ // Add program name if available (custom parameter)
54+ if ( userProgram ) {
55+ console . log ( 'userProgram' , userProgram ) ;
56+ eventParams . program = userProgram ;
57+ }
58+
59+ // Use gtag directly to send event with custom parameters
60+ // This ensures custom parameters like 'program' are sent to GA4
61+ if ( window . gtag && typeof window . gtag === 'function' ) {
62+ window . gtag ( 'event' , action , eventParams ) ;
63+ } else {
64+ // Fallback to ReactGA.event if gtag is not available
65+ ReactGA . event ( {
66+ action,
67+ category,
68+ label,
69+ value,
70+ } ) ;
71+ }
2872} ;
0 commit comments