refactor(analytics): abstract analytics into provider pattern
Some checks failed
Build and Deploy / build (push) Has been cancelled
Some checks failed
Build and Deploy / build (push) Has been cancelled
- Add type-safe AnalyticsEvent union types - Create AnalyticsProvider interface for pluggable analytics backends - Implement OpenPanelProvider and RybbitProvider adapters - Create AnalyticsTracker that fans out events to all providers - Simplifies adding new analytics platforms in the future
This commit is contained in:
28
src/lib/analytics/hooks/useAnalytics.ts
Normal file
28
src/lib/analytics/hooks/useAnalytics.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useOpenPanel } from "@openpanel/nextjs";
|
||||
import { getTracker, AnalyticsTracker } from "../core/AnalyticsTracker";
|
||||
import { OpenPanelProvider } from "../providers/OpenPanelProvider";
|
||||
import { RybbitProvider } from "../providers/RybbitProvider";
|
||||
|
||||
let initialized = false;
|
||||
|
||||
export function useAnalytics(): AnalyticsTracker {
|
||||
const op = useOpenPanel();
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
const trackerRef = useRef<AnalyticsTracker | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialized) {
|
||||
const tracker = getTracker();
|
||||
tracker.addProvider(new OpenPanelProvider(op));
|
||||
tracker.addProvider(new RybbitProvider());
|
||||
trackerRef.current = tracker;
|
||||
initialized = true;
|
||||
setIsReady(true);
|
||||
}
|
||||
}, [op]);
|
||||
|
||||
return trackerRef.current || getTracker();
|
||||
}
|
||||
Reference in New Issue
Block a user