Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 5x 5x 5x 5x 12x 12x 5x 2x 2x 2x 3x 3x 1x 1x 1x 5x 2x 12x 12x 5x 5x 3x 3x 12x 12x 5x 4x 4x 1x 1x 1x 4x 3x 3x 4x 5x 5x 5x 5x 12x 12x 12x | import { useCallback, useEffect, useRef, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { getUnreadNotificationCount } from '@/services/notificationService';
import {
NOTIFICATION_UNREAD_COUNT_EVENT,
type NotificationUnreadCountEventDetail,
} from '@/utils/notificationUnreadEvents';
const POLL_INTERVAL_MS = 60_000;
export interface UnreadCountViewModel {
unreadCount: number;
refresh: () => Promise<void>;
}
export function useUnreadCountViewModel(): UnreadCountViewModel {
const { token } = useAuth();
const [unreadCount, setUnreadCount] = useState(0);
const isMountedRef = useRef(true);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
const refresh = useCallback(async () => {
if (!token) {
setUnreadCount(0);
return;
}
try {
const response = await getUnreadNotificationCount(token);
if (isMountedRef.current) {
setUnreadCount(response.unread_count);
}
} catch {
// Best-effort polling; silently ignore transient failures
}
}, [token]);
useEffect(() => {
refresh();
if (!token) return;
const id = window.setInterval(refresh, POLL_INTERVAL_MS);
return () => window.clearInterval(id);
}, [refresh, token]);
useEffect(() => {
const handleUnreadCountEvent = (event: Event) => {
const detail = (event as CustomEvent<NotificationUnreadCountEventDetail>).detail;
if (typeof detail?.count === 'number') {
setUnreadCount(Math.max(0, detail.count));
return;
}
if (typeof detail?.delta === 'number') {
setUnreadCount((current) => Math.max(0, current + detail.delta!));
}
};
window.addEventListener(NOTIFICATION_UNREAD_COUNT_EVENT, handleUnreadCountEvent);
return () => {
window.removeEventListener(NOTIFICATION_UNREAD_COUNT_EVENT, handleUnreadCountEvent);
};
}, []);
return { unreadCount, refresh };
}
|