1
0
Fork 0
blog/src/features/Web3/hooks/useFetchTokens/useFetchTokens.tsx

33 lines
1008 B
TypeScript
Raw Normal View History

2023-11-01 15:22:43 +01:00
import { useEffect, useState } from 'react'
2023-11-06 14:37:27 +01:00
import useSWR, { type SWRResponse } from 'swr'
2024-03-14 14:18:21 +01:00
import { useAccount, useChains } from 'wagmi'
2023-11-05 16:31:09 +01:00
import type { GetToken } from './types'
2023-11-01 15:22:43 +01:00
2023-11-01 23:16:02 +01:00
const fetcher = (url: string) => fetch(url).then((res) => res.json())
2023-11-01 23:25:33 +01:00
const apiUrl = import.meta.env.PUBLIC_WEB3_API_URL
2023-11-01 23:16:02 +01:00
2023-11-01 15:22:43 +01:00
//
2023-11-01 16:31:29 +01:00
// Wrapper for fetching user tokens with swr.
2023-11-01 15:22:43 +01:00
//
2023-11-06 14:37:27 +01:00
export function useFetchTokens(): SWRResponse<GetToken[] | undefined, Error> {
2023-11-01 15:22:43 +01:00
const { address } = useAccount()
2024-03-14 14:18:21 +01:00
const chains = useChains()
const [url, setUrl] = useState<string | undefined>()
2023-11-01 15:22:43 +01:00
const fetchResults = useSWR<GetToken[] | undefined>(url, fetcher)
// Set url only after we have all data loaded on client,
// preventing initial fetch.
useEffect(() => {
2024-03-14 14:18:21 +01:00
if (!address || !chains) {
2023-11-05 16:31:09 +01:00
setUrl(undefined)
return
}
2023-11-01 15:22:43 +01:00
2024-03-14 14:18:21 +01:00
const chainIds = chains.map((chain) => chain.id).join(',')
const url = `${apiUrl}/balance?address=${address}&chainIds=${chainIds}`
2023-11-01 15:22:43 +01:00
setUrl(url)
2024-03-14 14:18:21 +01:00
}, [address, chains])
2023-11-01 15:22:43 +01:00
2023-11-01 16:31:29 +01:00
return fetchResults
2023-11-01 15:22:43 +01:00
}