diff --git a/apps/main/src/hooks/useChatUnread.ts b/apps/main/src/hooks/useChatUnread.ts new file mode 100644 index 0000000..ff7f806 --- /dev/null +++ b/apps/main/src/hooks/useChatUnread.ts @@ -0,0 +1,37 @@ +import { useQuery } from "@tanstack/react-query"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; + +const CHAT_API_BASE = import.meta.env.VITE_CHAT_API_URL as string; + +interface UnreadCount { + channel_id: string; + unread_count: number; +} + +export function useChatUnread() { + const { session } = useSession(); + const token = session?.access_token; + + const { data } = useQuery({ + queryKey: ["chat-unread"], + queryFn: async (): Promise => { + const res = await fetch(`${CHAT_API_BASE}/chat/unread`, { + headers: { Authorization: `Bearer ${token}` }, + }); + if (!res.ok) return []; + const json = await res.json() as { unread: UnreadCount[] }; + return json.unread; + }, + enabled: !!token, + refetchInterval: 30_000, + refetchOnWindowFocus: true, + }); + + return { + unreadCounts: data ?? [], + getUnreadCount: (channelId: string) => + data?.find((u) => u.channel_id === channelId)?.unread_count ?? 0, + hasUnread: (channelId: string) => + (data?.find((u) => u.channel_id === channelId)?.unread_count ?? 0) > 0, + }; +}