import { useNostr } from '@nostrify/react'; import { useQuery } from '@tanstack/react-query'; /** * Batch comment counts for a list of root event IDs. * * Queries kind 1111 (NIP-22 comments) that reference any of the given event * ids via the uppercase root `#E` tag (and also tallies lowercase `e` for * resilience), returning a Map of eventId -> comment count. * * This replaces the previous (incorrect) usage of `useComments(string[])` — * `useComments` only accepts a SINGLE NostrEvent|URL root, so passing an array * silently produced a bad query and a `.filter` on the wrong shape. */ export function useCommentCounts(eventIds: string[]) { const { nostr } = useNostr(); // Stable key regardless of order/dupes. const ids = Array.from(new Set(eventIds)).sort(); return useQuery({ queryKey: ['comment-counts', ids], enabled: ids.length > 0, staleTime: 60 * 1000, queryFn: async (c) => { const signal = AbortSignal.any([c.signal, AbortSignal.timeout(6000)]); const events = await nostr.query( [{ kinds: [1111], '#E': ids, limit: 1000 }], { signal }, ); const counts = new Map(); for (const ev of events) { // Prefer the uppercase root tag; fall back to lowercase parent tag. const root = ev.tags.find(([n]) => n === 'E')?.[1] ?? ev.tags.find(([n]) => n === 'e')?.[1]; if (root && ids.includes(root)) { counts.set(root, (counts.get(root) ?? 0) + 1); } } return counts; }, }); }