-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathPlausibleAnalytics.tsx
More file actions
49 lines (44 loc) · 1.45 KB
/
PlausibleAnalytics.tsx
File metadata and controls
49 lines (44 loc) · 1.45 KB
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
41
42
43
44
45
46
47
48
49
import {createContext, FC, PropsWithChildren, useEffect, useMemo} from "react";
import Plausible, {EventOptions, PlausibleOptions} from "plausible-tracker";
/**
* PlausibleAnalytics is responsible for tracking custom event goals.
*
* To get an instance of PlausibleAnalytics, you should use the useContext hook:
* @example
* const analytics = useContext(PlausibleAnalyticsContext);
*/
export interface PlausibleAnalytics {
/**
* Tracks a new event.
* @param eventName - name of the event to track
* @param options - callback and additional event props
* @param eventData
*/
trackEvent: (
eventName: string,
options?: EventOptions,
eventData?: PlausibleOptions
) => void;
}
export const PlausibleAnalyticsContext = createContext<PlausibleAnalytics | null>(null);
export interface PlausibleAnalyticsProps {
domain: string;
apiHost: string;
}
/**
* PlausibleAnalytics is created using PlausibleAnalyticsProvider component
*/
export const PlausibleAnalyticsProvider: FC<PropsWithChildren<PlausibleAnalyticsProps>> = ({children, domain, apiHost}) => {
const plausible = useMemo(() => {
return Plausible({
domain,
apiHost
})
}, [domain, apiHost]);
useEffect(() => {
plausible.enableAutoPageviews();
}, [plausible]);
return <PlausibleAnalyticsContext.Provider value={plausible}>
{children}
</PlausibleAnalyticsContext.Provider>
};