From 2f6e4f0b3cb96f0b15419c10f3e085fa818ac7c4 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Thu, 26 Oct 2023 20:45:57 +0100 Subject: [PATCH] refactor --- .../Web3Donation/components/Tokens/Select.tsx | 28 ++------------- .../Sponsor/Web3Donation/hooks/useTokens.tsx | 36 +++++++++++++++++++ 2 files changed, 39 insertions(+), 25 deletions(-) create mode 100644 src/components/Sponsor/Web3Donation/hooks/useTokens.tsx diff --git a/src/components/Sponsor/Web3Donation/components/Tokens/Select.tsx b/src/components/Sponsor/Web3Donation/components/Tokens/Select.tsx index 27a86b53..39702560 100644 --- a/src/components/Sponsor/Web3Donation/components/Tokens/Select.tsx +++ b/src/components/Sponsor/Web3Donation/components/Tokens/Select.tsx @@ -2,35 +2,13 @@ import * as Select from '@radix-ui/react-select' import './Select.css' import { SelectItem } from './SelectItem' import { ChevronDown, ChevronsDown, ChevronsUp } from '@images/components/react' -import { useEffect, useState } from 'react' -import { getBalance } from '../../api/getBalance' -import { useAccount, useNetwork } from 'wagmi' +import { useTokens } from '../../hooks/useTokens' export function TokenSelect() { - const { address } = useAccount() - const { chain } = useNetwork() - - const [tokens, setTokens] = useState() - - useEffect(() => { - if (!address || !chain) return - - async function getTokens() { - try { - const response = await getBalance(address) - const tokens = response.filter( - (token: any) => parseInt(token.chainId) === chain?.id - ) - setTokens(tokens) - } catch (error) { - console.error((error as Error).message) - } - } - getTokens() - }, [address, chain]) + const { data: tokens } = useTokens() return ( - + diff --git a/src/components/Sponsor/Web3Donation/hooks/useTokens.tsx b/src/components/Sponsor/Web3Donation/hooks/useTokens.tsx new file mode 100644 index 00000000..22d54130 --- /dev/null +++ b/src/components/Sponsor/Web3Donation/hooks/useTokens.tsx @@ -0,0 +1,36 @@ +import { useState, useEffect } from 'react' +import { useAccount, useNetwork } from 'wagmi' +import { getBalance } from '../api/getBalance' + +export function useTokens() { + const { address } = useAccount() + const { chain } = useNetwork() + + const [data, setData] = useState() + const [isLoading, setIsLoading] = useState() + const [isError, setIsError] = useState() + + useEffect(() => { + if (!address || !chain) return + + async function getTokens() { + setIsLoading(true) + + try { + const response = await getBalance(address) + const tokens = response.filter( + (token: any) => parseInt(token.chainId) === chain?.id + ) + setData(tokens) + setIsLoading(false) + } catch (error) { + setIsError(true) + setIsLoading(false) + console.error((error as Error).message) + } + } + getTokens() + }, [address, chain]) + + return { data, isLoading, isError } +}