diff --git a/xtablo-expo/hooks/chatUnread.ts b/xtablo-expo/hooks/chatUnread.ts new file mode 100644 index 0000000..bb2bcfe --- /dev/null +++ b/xtablo-expo/hooks/chatUnread.ts @@ -0,0 +1,31 @@ +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 => { + 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, + }; +}