degmods.com/src/hooks/useComments.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

import {
2024-10-14 19:20:43 +05:00
NDKFilter,
NDKKind,
NDKSubscription,
NDKSubscriptionCacheUsage
} from '@nostr-dev-kit/ndk'
import { useEffect, useState } from 'react'
import { CommentEvent, ModDetails } from 'types'
2024-10-14 19:20:43 +05:00
import { useNDKContext } from './useNDKContext'
export const useComments = (mod: ModDetails) => {
2024-10-14 19:20:43 +05:00
const { ndk } = useNDKContext()
const [commentEvents, setCommentEvents] = useState<CommentEvent[]>([])
2024-10-14 19:20:43 +05:00
useEffect(() => {
let subscription: NDKSubscription // Define the subscription variable here for cleanup
2024-10-14 19:20:43 +05:00
const setupSubscription = async () => {
const filter: NDKFilter = {
kinds: [NDKKind.Text],
'#a': [mod.aTag],
'#p': [mod.author]
2024-10-14 19:20:43 +05:00
}
subscription = ndk.subscribe(filter, {
closeOnEose: false,
cacheUsage: NDKSubscriptionCacheUsage.CACHE_FIRST
})
console.log('ndk.pool.urls() :>> ', ndk.pool.urls())
2024-10-14 19:20:43 +05:00
subscription.on('event', (ndkEvent) => {
setCommentEvents((prev) => {
2024-10-14 19:20:43 +05:00
if (prev.find((e) => e.id === ndkEvent.id)) {
return [...prev]
}
2024-10-14 19:20:43 +05:00
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]
})
2024-10-14 19:20:43 +05:00
})
subscription.start()
}
setupSubscription()
// Cleanup function to stop the subscription on unmount
return () => {
if (subscription) {
subscription.stop()
}
2024-10-14 19:20:43 +05:00
}
}, [mod.aTag, mod.author, ndk])
return {
commentEvents,
setCommentEvents
}
}