1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-06-28 16:48:00 +02:00
blog/src/features/Web3/hooks/useTokens/useTokens.tsx

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-10-26 21:45:57 +02:00
import { useState, useEffect } from 'react'
import { useAccount, useNetwork } from 'wagmi'
2023-10-29 15:36:48 +01:00
import { getTokens } from './getTokens'
import type { GetToken } from './types'
2023-10-26 21:45:57 +02:00
export function useTokens() {
const { address } = useAccount()
const { chain } = useNetwork()
2023-10-28 18:08:46 +02:00
const [data, setData] = useState<GetToken[]>()
2023-10-26 21:45:57 +02:00
const [isLoading, setIsLoading] = useState<boolean>()
const [isError, setIsError] = useState<boolean>()
useEffect(() => {
2023-10-29 15:36:48 +01:00
const abortController = new AbortController()
const { signal } = abortController
2023-10-28 13:55:30 +02:00
async function init() {
2023-10-29 15:36:48 +01:00
if (!address || !chain?.id) return
2023-10-26 21:45:57 +02:00
setIsLoading(true)
try {
2023-10-29 15:36:48 +01:00
const tokens = await getTokens(address, chain.id, signal)
2023-10-26 21:45:57 +02:00
setData(tokens)
setIsLoading(false)
2023-10-29 15:36:48 +01:00
} catch (error: any) {
2023-10-26 21:45:57 +02:00
setIsError(true)
setIsLoading(false)
2023-10-29 15:36:48 +01:00
if ((error as Error).name !== 'AbortError') {
console.error((error as Error).message)
}
2023-10-26 21:45:57 +02:00
}
}
2023-10-28 13:55:30 +02:00
init()
2023-10-29 15:36:48 +01:00
return () => {
abortController.abort()
setData(undefined)
setIsLoading(undefined)
setIsError(undefined)
}
}, [address, chain?.id])
2023-10-26 21:45:57 +02:00
return { data, isLoading, isError }
}