|
| 1 | +import { useCallback } from 'react'; |
| 2 | +import { createState, useState } from '@hookstate/core'; |
| 3 | +import * as ReactGA from 'react-ga'; |
| 4 | + |
| 5 | +import type { GAEffect, GAReturn } from './types'; |
| 6 | + |
| 7 | +const enabledState = createState<boolean>(false); |
| 8 | + |
| 9 | +export function useGoogleAnalytics(): GAReturn { |
| 10 | + const enabled = useState<boolean>(enabledState); |
| 11 | + |
| 12 | + const useAnalytics = useCallback((effect: GAEffect): void => { |
| 13 | + if (typeof window !== 'undefined' && enabled.value) { |
| 14 | + if (typeof effect === 'function') { |
| 15 | + effect(ReactGA); |
| 16 | + } |
| 17 | + } |
| 18 | + }, []); |
| 19 | + |
| 20 | + const trackEvent = useCallback((e: ReactGA.EventArgs) => { |
| 21 | + useAnalytics(ga => { |
| 22 | + if (process.env.NODE_ENV === 'production') { |
| 23 | + ga.event(e); |
| 24 | + } else { |
| 25 | + console.log( |
| 26 | + `%cEvent %c${JSON.stringify(e)}`, |
| 27 | + 'background: green; color: black; padding: 0.5rem; font-size: 0.75rem;', |
| 28 | + 'background: black; color: green; padding: 0.5rem; font-size: 0.75rem; font-weight: bold;', |
| 29 | + ); |
| 30 | + } |
| 31 | + }); |
| 32 | + }, []); |
| 33 | + |
| 34 | + const trackPage = useCallback((path: string) => { |
| 35 | + useAnalytics(ga => { |
| 36 | + if (process.env.NODE_ENV === 'production') { |
| 37 | + ga.pageview(path); |
| 38 | + } else { |
| 39 | + console.log( |
| 40 | + `%cPage View %c${path}`, |
| 41 | + 'background: blue; color: white; padding: 0.5rem; font-size: 0.75rem;', |
| 42 | + 'background: white; color: blue; padding: 0.5rem; font-size: 0.75rem; font-weight: bold;', |
| 43 | + ); |
| 44 | + } |
| 45 | + }); |
| 46 | + }, []); |
| 47 | + |
| 48 | + const trackModal = useCallback((path: string) => { |
| 49 | + useAnalytics(ga => { |
| 50 | + if (process.env.NODE_ENV === 'production') { |
| 51 | + ga.modalview(path); |
| 52 | + } else { |
| 53 | + console.log( |
| 54 | + `%cModal View %c${path}`, |
| 55 | + 'background: red; color: white; padding: 0.5rem; font-size: 0.75rem;', |
| 56 | + 'background: white; color: red; padding: 0.5rem; font-size: 0.75rem; font-weight: bold;', |
| 57 | + ); |
| 58 | + } |
| 59 | + }); |
| 60 | + }, []); |
| 61 | + |
| 62 | + const initialize = useCallback((trackingId: string, debug: boolean) => { |
| 63 | + if (typeof trackingId !== 'string') { |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + enabled.set(true); |
| 68 | + |
| 69 | + const initializeOpts = { titleCase: false } as ReactGA.InitializeOptions; |
| 70 | + |
| 71 | + if (debug) { |
| 72 | + initializeOpts.debug = true; |
| 73 | + } |
| 74 | + |
| 75 | + useAnalytics(ga => { |
| 76 | + ga.initialize(trackingId, initializeOpts); |
| 77 | + }); |
| 78 | + }, []); |
| 79 | + |
| 80 | + return { trackEvent, trackModal, trackPage, initialize, ga: ReactGA }; |
| 81 | +} |
0 commit comments