OpChan/packages/react/src/provider/OpChanProvider.tsx

74 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-09-18 17:02:11 +05:30
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { OpChanClient } from '@opchan/core';
2025-09-23 16:32:54 +05:30
import { localDatabase } from '@opchan/core';
2025-09-18 22:04:40 +05:30
import { ClientProvider } from '../contexts/ClientContext';
2025-09-18 17:02:11 +05:30
import { AuthProvider } from '../contexts/AuthContext';
import { ForumProvider } from '../contexts/ForumContext';
import { ModerationProvider } from '../contexts/ModerationContext';
2025-09-22 17:49:02 +05:30
import { IdentityProvider } from '../contexts/IdentityContext';
2025-09-18 17:02:11 +05:30
export interface OpChanProviderProps {
ordiscanApiKey: string;
debug?: boolean;
children: React.ReactNode;
}
export const OpChanProvider: React.FC<OpChanProviderProps> = ({
ordiscanApiKey,
debug,
children,
}) => {
const [isReady, setIsReady] = useState(false);
const clientRef = useRef<OpChanClient | null>(null);
useEffect(() => {
let cancelled = false;
const init = async () => {
if (typeof window === 'undefined') return; // SSR guard
// Configure environment and create client
const client = new OpChanClient({
ordiscanApiKey,
});
clientRef.current = client;
// Open local DB early for warm cache
await localDatabase.open().catch(console.error);
try {
await client.messageManager.initialize();
} catch (e) {
console.error('Failed to initialize message manager:', e);
}
2025-09-18 17:02:11 +05:30
if (!cancelled) setIsReady(true);
};
init();
return () => {
cancelled = true;
};
}, [ordiscanApiKey, debug]);
const providers = useMemo(() => {
if (!isReady || !clientRef.current) return null;
return (
2025-09-18 22:04:40 +05:30
<ClientProvider client={clientRef.current}>
2025-09-22 17:49:02 +05:30
<IdentityProvider client={clientRef.current}>
2025-09-23 16:32:54 +05:30
<AuthProvider>
2025-09-22 17:49:02 +05:30
<ModerationProvider>
2025-09-23 16:32:54 +05:30
<ForumProvider>{children}</ForumProvider>
2025-09-22 17:49:02 +05:30
</ModerationProvider>
</AuthProvider>
</IdentityProvider>
2025-09-18 22:04:40 +05:30
</ClientProvider>
2025-09-18 17:02:11 +05:30
);
}, [isReady, children]);
return providers || null;
};