import { NDKFilter, NDKKind, NDKSubscription, NDKSubscriptionCacheUsage } from '@nostr-dev-kit/ndk' import { useEffect, useState } from 'react' import { CommentEvent, ModDetails } from 'types' import { useNDKContext } from './useNDKContext' export const useComments = (mod: ModDetails) => { const { ndk } = useNDKContext() const [commentEvents, setCommentEvents] = useState([]) useEffect(() => { let subscription: NDKSubscription // Define the subscription variable here for cleanup const setupSubscription = async () => { const filter: NDKFilter = { kinds: [NDKKind.Text], '#a': [mod.aTag], '#p': [mod.author] } subscription = ndk.subscribe(filter, { closeOnEose: false, cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST }) console.log('ndk.pool.urls() :>> ', ndk.pool.urls()) subscription.on('event', (ndkEvent) => { setCommentEvents((prev) => { if (prev.find((e) => e.id === ndkEvent.id)) { return [...prev] } const commentEvent: CommentEvent = { kind: NDKKind.Text, tags: ndkEvent.tags, content: ndkEvent.content, created_at: ndkEvent.created_at!, pubkey: ndkEvent.pubkey, id: ndkEvent.id, sig: ndkEvent.sig! } return [commentEvent, ...prev] }) }) subscription.start() } setupSubscription() // Cleanup function to stop the subscription on unmount return () => { if (subscription) { subscription.stop() } } }, [mod.aTag, mod.author, ndk]) return { commentEvents, setCommentEvents } }