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

38 lines 1.3 kB
import { useContext, useEffect, useRef, useState } from 'react'; import {} from '../../utils/debugChannel'; import { GAContext } from '../context'; export function useGADebugStream(limit = 50) { const context = useContext(GAContext); if (!context) { throw new Error('useGADebugStream must be used inside GAProvider'); } const validLimit = Math.max(1, Math.floor(limit)); const [events, setEvents] = useState([]); const limitRef = useRef(validLimit); useEffect(() => { limitRef.current = validLimit; setEvents((prev) => { if (prev.length > validLimit) { return prev.slice(-validLimit); } return prev; }); }, [validLimit]); useEffect(() => { const unsubscribe = context.debugChannel.subscribe((event) => { setEvents((prev) => { const next = [...prev, event]; const currentLimit = limitRef.current; if (next.length > currentLimit) { return next.slice(-currentLimit); } return next; }); }); return () => { unsubscribe(); }; }, [context.debugChannel]); return events; } //# sourceMappingURL=useGADebugStream.js.map