Something went wrong. Try again.
A Bsky-like frontend using the atprotocol natively.
Something went wrong. Try again.
1.8 kB · 67 lines
TSX
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import { useState, useCallback, useEffect, useRef, type ReactNode } from 'react';import { atprotoClient } from '../api/client';import { useAuth } from '../auth/useAuth';import { NotificationCountContext } from './notificationCountContext';
const POLL_INTERVAL = 30_000;
export function NotificationCountProvider({ children }: { children: ReactNode }) { const [unreadCount, setUnreadCount] = useState(0); const { session } = useAuth(); const prevSessionDidRef = useRef<string | undefined>(undefined); const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
if (session?.did !== prevSessionDidRef.current) { prevSessionDidRef.current = session?.did; if (!session) setUnreadCount(0); }
const refreshCount = useCallback(async () => { try { const resp = await atprotoClient.getUnreadCount(); setUnreadCount(resp.count); } catch { } }, []);
const markSeen = useCallback(async () => { setUnreadCount(0); }, []);
useEffect(() => { if (!session) { return; }
intervalRef.current = setInterval(() => { void refreshCount(); }, POLL_INTERVAL);
const initialTimeout = setTimeout(() => void refreshCount(), 0);
return () => { if (intervalRef.current) { clearInterval(intervalRef.current); } clearTimeout(initialTimeout); }; }, [session, refreshCount]);
useEffect(() => { const handler = () => setUnreadCount(0); window.addEventListener('foxsky:notifications-seen', handler); return () => window.removeEventListener('foxsky:notifications-seen', handler); }, []);
return ( <NotificationCountContext.Provider value={{ unreadCount, refreshCount, markSeen }}> {children} </NotificationCountContext.Provider> );}