71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
import { useCallback, useEffect, useState } from 'react'
|
|
import { fetchAuthorByHashId } from '@/lib/authorQueries'
|
|
import { getSeriesByAuthor } from '@/lib/seriesQueries'
|
|
import { getAuthorSponsoring } from '@/lib/sponsoring'
|
|
import { nostrService } from '@/lib/nostr'
|
|
import type { AuthorPresentationArticle, Series } from '@/types/nostr'
|
|
|
|
async function loadAuthorData(hashId: string): Promise<{
|
|
pres: AuthorPresentationArticle | null
|
|
seriesList: Series[]
|
|
sponsoring: number
|
|
}> {
|
|
const pool = nostrService.getPool()
|
|
if (!pool) {
|
|
throw new Error('Pool not initialized')
|
|
}
|
|
|
|
const pres = await fetchAuthorByHashId(pool, hashId)
|
|
if (!pres) {
|
|
return { pres: null, seriesList: [], sponsoring: 0 }
|
|
}
|
|
|
|
const [seriesList, sponsoring] = await Promise.all([
|
|
getSeriesByAuthor(pres.pubkey),
|
|
getAuthorSponsoring(pres.pubkey),
|
|
])
|
|
|
|
return { pres, seriesList, sponsoring }
|
|
}
|
|
|
|
export function useAuthorData(hashIdOrPubkey: string): {
|
|
presentation: AuthorPresentationArticle | null
|
|
series: Series[]
|
|
totalSponsoring: number
|
|
loading: boolean
|
|
error: string | null
|
|
reload: () => Promise<void>
|
|
} {
|
|
const [presentation, setPresentation] = useState<AuthorPresentationArticle | null>(null)
|
|
const [series, setSeries] = useState<Series[]>([])
|
|
const [totalSponsoring, setTotalSponsoring] = useState<number>(0)
|
|
const [loading, setLoading] = useState(true)
|
|
const [error, setError] = useState<string | null>(null)
|
|
|
|
const reload = useCallback(async (): Promise<void> => {
|
|
if (!hashIdOrPubkey) {
|
|
return
|
|
}
|
|
|
|
setLoading(true)
|
|
setError(null)
|
|
|
|
try {
|
|
const { pres, seriesList, sponsoring } = await loadAuthorData(hashIdOrPubkey)
|
|
setPresentation(pres)
|
|
setSeries(seriesList)
|
|
setTotalSponsoring(sponsoring)
|
|
} catch (e) {
|
|
setError(e instanceof Error ? e.message : 'Erreur lors du chargement')
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}, [hashIdOrPubkey])
|
|
|
|
useEffect(() => {
|
|
void reload()
|
|
}, [hashIdOrPubkey, reload])
|
|
|
|
return { presentation, series, totalSponsoring, loading, error, reload }
|
|
}
|