story-research-zapwall/hooks/useAuthorsProfiles.ts
2026-01-09 13:13:24 +01:00

59 lines
1.6 KiB
TypeScript

import { useEffect, useState, useMemo } from 'react'
import type { NostrProfile } from '@/types/nostr'
import { nostrService } from '@/lib/nostr'
interface AuthorProfile extends NostrProfile {
pubkey: string
}
export function useAuthorsProfiles(authorPubkeys: string[]): {
profiles: Map<string, AuthorProfile>
loading: boolean
} {
const [profiles, setProfiles] = useState<Map<string, AuthorProfile>>(new Map())
const [loading, setLoading] = useState(true)
const pubkeysKey = useMemo(() => [...authorPubkeys].sort().join(','), [authorPubkeys])
useEffect(() => {
const loadProfiles = async (): Promise<void> => {
if (authorPubkeys.length === 0) {
setProfiles(new Map())
setLoading(false)
return
}
setLoading(true)
const profilesMap = new Map<string, AuthorProfile>()
const profilePromises = authorPubkeys.map(async (pubkey) => {
try {
const profile = await nostrService.getProfile(pubkey)
return {
pubkey,
profile: profile ?? { pubkey },
}
} catch (loadError) {
console.error(`Error loading profile for ${pubkey}:`, loadError)
return {
pubkey,
profile: { pubkey },
}
}
})
const results = await Promise.all(profilePromises)
results.forEach(({ pubkey, profile }) => {
profilesMap.set(pubkey, profile)
})
setProfiles(profilesMap)
setLoading(false)
}
void loadProfiles()
}, [pubkeysKey, authorPubkeys])
return { profiles, loading }
}