useFetchProfile.tsx raw

   1  import { Pubkey } from '@/domain'
   2  import { useNostr } from '@/providers/NostrProvider'
   3  import client from '@/services/client.service'
   4  import { TProfile } from '@/types'
   5  import { useEffect, useState } from 'react'
   6  
   7  export function useFetchProfile(id?: string) {
   8    const { profile: currentAccountProfile } = useNostr()
   9    const [isFetching, setIsFetching] = useState(true)
  10    const [error, setError] = useState<Error | null>(null)
  11    const [profile, setProfile] = useState<TProfile | null>(null)
  12    const [pubkey, setPubkey] = useState<string | null>(null)
  13  
  14    useEffect(() => {
  15      setProfile(null)
  16      setPubkey(null)
  17      const fetchProfile = async () => {
  18        setIsFetching(true)
  19        try {
  20          if (!id) {
  21            setIsFetching(false)
  22            setError(new Error('No id provided'))
  23            return
  24          }
  25  
  26          const pubkey = Pubkey.tryFromString(id)?.hex ?? id
  27          setPubkey(pubkey)
  28          const profile = await client.fetchProfile(id)
  29          if (profile) {
  30            setProfile(profile)
  31          }
  32        } catch (err) {
  33          setError(err as Error)
  34        } finally {
  35          setIsFetching(false)
  36        }
  37      }
  38  
  39      fetchProfile()
  40    }, [id])
  41  
  42    useEffect(() => {
  43      if (currentAccountProfile && pubkey === currentAccountProfile.pubkey) {
  44        setProfile(currentAccountProfile)
  45      }
  46    }, [currentAccountProfile, pubkey])
  47  
  48    return { isFetching, error, profile }
  49  }
  50