feat(chat): add useChatUnread hook for polling unread counts
This commit is contained in:
parent
2833b4b2c1
commit
db59316dc3
1 changed files with 37 additions and 0 deletions
37
apps/main/src/hooks/useChatUnread.ts
Normal file
37
apps/main/src/hooks/useChatUnread.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
Loading…
Reference in a new issue