UNPKG

@shopana/ga

Version:

Type-safe Google Analytics 4 (GA4) tracking library for React and Next.js with ecommerce support, event batching, and SSR compatibility

36 lines 1.28 kB
import { useEffect, useRef } from 'react'; import { useGATracker } from './useAnalyticsClient'; export function useAutoPageView(router) { const tracker = useGATracker(); const trackerRef = useRef(tracker); useEffect(() => { trackerRef.current = tracker; }, [tracker]); useEffect(() => { if (!router?.events?.on) { return; } const initialPageViewTrackedRef = { current: false }; const handler = (path) => { void trackerRef.current.pageView({ path }); initialPageViewTrackedRef.current = true; }; const unsubscribe = router.events.on('routeChangeComplete', handler); void Promise.resolve().then(() => { if (!initialPageViewTrackedRef.current) { const initialPath = router.currentPath ?? (typeof window !== 'undefined' ? window.location.pathname : '/'); handler(initialPath); } }); return () => { if (typeof unsubscribe === 'function') { unsubscribe(); } else { router.events?.off?.('routeChangeComplete', handler); } }; }, [router]); } //# sourceMappingURL=useAutoPageView.js.map