31 lines
965 B
TypeScript
31 lines
965 B
TypeScript
import { useQuery } from "@tanstack/react-query";
|
|
import { useAuthStore } from "@/stores/auth";
|
|
import { UnreadCount } from "@/types/chat.types";
|
|
|
|
const CHAT_API_BASE = process.env.EXPO_PUBLIC_CHAT_API_URL as string;
|
|
|
|
export function useChatUnread() {
|
|
const session = useAuthStore((state) => state.session);
|
|
const token = session?.access_token;
|
|
|
|
const { data, refetch } = 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,
|
|
});
|
|
|
|
return {
|
|
unreadCounts: data ?? [],
|
|
getUnreadCount: (channelId: string) =>
|
|
data?.find((u) => u.channel_id === channelId)?.unread_count ?? 0,
|
|
refetch,
|
|
};
|
|
}
|