useSearchProfiles.tsx raw

   1  import { useFeed } from '@/providers/FeedProvider'
   2  import client from '@/services/client.service'
   3  import storage from '@/services/local-storage.service'
   4  import { TProfile } from '@/types'
   5  import { useEffect, useState } from 'react'
   6  import { useFetchRelayInfos } from './useFetchRelayInfos'
   7  
   8  export function useSearchProfiles(search: string, limit: number) {
   9    const { relayUrls } = useFeed()
  10    const { searchableRelayUrls } = useFetchRelayInfos(relayUrls)
  11    const [isFetching, setIsFetching] = useState(true)
  12    const [error, setError] = useState<Error | null>(null)
  13    const [profiles, setProfiles] = useState<TProfile[]>([])
  14  
  15    useEffect(() => {
  16      const fetchProfiles = async () => {
  17        if (!search) {
  18          setProfiles([])
  19          return
  20        }
  21  
  22        setIsFetching(true)
  23        setProfiles([])
  24        try {
  25          const profiles = await client.searchProfilesFromLocal(search, limit)
  26          setProfiles(profiles)
  27          if (profiles.length >= limit) {
  28            return
  29          }
  30          const existingPubkeys = new Set(profiles.map((profile) => profile.pubkey))
  31          const fetchedProfiles = await client.searchProfiles(
  32            searchableRelayUrls.concat(storage.getSearchRelays()).slice(0, 4),
  33            {
  34              search,
  35              limit
  36            }
  37          )
  38          if (fetchedProfiles.length) {
  39            fetchedProfiles.forEach((profile) => {
  40              if (existingPubkeys.has(profile.pubkey)) {
  41                return
  42              }
  43              existingPubkeys.add(profile.pubkey)
  44              profiles.push(profile)
  45            })
  46            setProfiles([...profiles])
  47          }
  48        } catch (err) {
  49          setError(err as Error)
  50        } finally {
  51          setIsFetching(false)
  52        }
  53      }
  54  
  55      fetchProfiles()
  56    }, [searchableRelayUrls, search, limit])
  57  
  58    return { isFetching, error, profiles }
  59  }
  60