File size: 898 Bytes
572bb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
export interface GAEvent {
	hitType: "event";
	eventCategory: string;
	eventAction: string;
	eventLabel?: string;
	eventValue?: number;
}

// Send a Google Analytics event
export function sendAnalyticsEvent({
	eventCategory,
	eventAction,
	eventLabel,
	eventValue,
}: Omit<GAEvent, "hitType">): void {
	// Mandatory fields
	const event: GAEvent = {
		hitType: "event",
		eventCategory,
		eventAction,
	};
	// Optional fields
	if (eventLabel) {
		event.eventLabel = eventLabel;
	}
	if (eventValue) {
		event.eventValue = eventValue;
	}

	// @ts-expect-error typescript doesn't know gtag is on the window object
	if (!!window?.gtag && typeof window?.gtag === "function") {
		// @ts-expect-error typescript doesn't know gtag is on the window object
		window?.gtag("event", eventAction, {
			event_category: event.eventCategory,
			event_label: event.eventLabel,
			value: event.eventValue,
		});
	}
}