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

34 lines
950 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-13 02:20:29 +01:00
import { useChainId, useAccount } 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> {
2024-03-13 02:20:29 +01:00
const chainId = useChainId()
2023-11-01 15:22:43 +01:00
const { address } = useAccount()
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-13 02:20:29 +01:00
if (!address || !chainId) {
2023-11-05 16:31:09 +01:00
setUrl(undefined)
return
}
2023-11-01 15:22:43 +01:00
2024-03-13 02:20:29 +01:00
const url = `${apiUrl}/balance?address=${address}&chainId=${chainId}`
2023-11-01 15:22:43 +01:00
setUrl(url)
2024-03-13 02:20:29 +01:00
}, [address, chainId])
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
}