mirror of https://github.com/kremalicious/blog.git
39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { useEffect, useState } from 'react'
|
|
import useSWR from 'swr'
|
|
import type { GetToken } from './types'
|
|
import { useNetwork, useAccount } from 'wagmi'
|
|
import { fetcher } from '@stores/fetcher'
|
|
import { $setSelectedToken } from '@features/Web3/stores/selectedToken'
|
|
|
|
//
|
|
// Wrapper for fetching user tokens with swr.
|
|
//
|
|
export function useTokens() {
|
|
const { chain } = useNetwork()
|
|
const { address } = useAccount()
|
|
|
|
const [url, setUrl] = useState<string | undefined>(undefined)
|
|
|
|
const fetchResults = useSWR<GetToken[] | undefined>(url, fetcher)
|
|
const { data: tokens } = fetchResults
|
|
|
|
// Set url only after we have all data loaded on client,
|
|
// preventing initial fetch.
|
|
useEffect(() => {
|
|
if (!address || !chain?.id) return
|
|
|
|
const url = `https://web3.kremalicious.com/api/balance?address=${address}&chainId=${chain?.id}`
|
|
setUrl(url)
|
|
}, [address, chain?.id])
|
|
|
|
// Set default token data to first item,
|
|
// which most of time is native token
|
|
useEffect(() => {
|
|
if (!tokens?.[0]?.chainId) return
|
|
|
|
$setSelectedToken(tokens?.[0])
|
|
}, [tokens?.[0]?.chainId])
|
|
|
|
return fetchResults
|
|
}
|