feat(core-analytics): add React provider and useAnalytics hook
Adds a ./react subpath export to @repo/core-analytics containing
<AnalyticsProvider value={IAnalytics}> and useAnalytics(): IAnalytics.
useAnalytics() throws AnalyticsContextError when called outside a provider.
React Testing Library test verifies track() flows through context using
RecordingAnalytics. Switches vitest config to pick up .tsx test files
via environmentMatchGlobs and extends tsconfig to react-library.json
for JSX support.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
33
packages/core-analytics/src/react/analytics-provider.tsx
Normal file
33
packages/core-analytics/src/react/analytics-provider.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { createContext, useContext, type ReactNode } from "react";
|
||||
import type { IAnalytics } from "../analytics.interface";
|
||||
|
||||
const AnalyticsContext = createContext<IAnalytics | null>(null);
|
||||
|
||||
export class AnalyticsContextError extends Error {
|
||||
constructor() {
|
||||
super("useAnalytics() must be called within an <AnalyticsProvider>.");
|
||||
this.name = "AnalyticsContextError";
|
||||
}
|
||||
}
|
||||
|
||||
export function AnalyticsProvider({
|
||||
value,
|
||||
children,
|
||||
}: {
|
||||
value: IAnalytics;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<AnalyticsContext.Provider value={value}>
|
||||
{children}
|
||||
</AnalyticsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAnalytics(): IAnalytics {
|
||||
const analytics = useContext(AnalyticsContext);
|
||||
if (analytics === null) {
|
||||
throw new AnalyticsContextError();
|
||||
}
|
||||
return analytics;
|
||||
}
|
||||
Reference in New Issue
Block a user