feat(chat): add useChatUnread hook for polling unread counts

This commit is contained in:
Arthur Belleville 2026-04-11 12:04:27 +02:00
parent 2833b4b2c1
commit db59316dc3
No known key found for this signature in database

View file

@ -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<UnreadCount[]> => {
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,
};
}