feat(currency-dropdown): check currency exist then change

This commit is contained in:
RadoslavDimchev 2024-04-24 19:33:00 +03:00 committed by Emil Ivanichkov
parent 1767b8e4db
commit f619446be7

View File

@ -22,14 +22,14 @@ const CurrencyDropdown = ({ depositAmount }: CurrencyDropdownProps) => {
const totalPrice = depositAmount * currentCurrencyAmount const totalPrice = depositAmount * currentCurrencyAmount
useEffect(() => { useEffect(() => {
fetchCurrencyPrice() fetchCurrencyPrice(currency)
}, [currency]) }, [])
const fetchCurrencyPrice = async () => { const fetchCurrencyPrice = async (newCurrency: string) => {
try { try {
setIsCurrencyLoading(true) setIsCurrencyLoading(true)
const response = await fetch( const response = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=${currency}`, `https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=${newCurrency}`,
{ {
headers: { headers: {
accept: 'application/json', accept: 'application/json',
@ -38,7 +38,13 @@ const CurrencyDropdown = ({ depositAmount }: CurrencyDropdownProps) => {
}, },
) )
const data = await response.json() const data = await response.json()
setCurrentCurrencyAmount(data.ethereum[currency])
if (!data.ethereum[newCurrency]) {
throw new Error('Currency not found')
}
setCurrentCurrencyAmount(data.ethereum[newCurrency])
dispatch({ type: 'currency/setCurrency', payload: newCurrency })
} catch (error) { } catch (error) {
console.error(error) console.error(error)
} finally { } finally {
@ -50,8 +56,12 @@ const CurrencyDropdown = ({ depositAmount }: CurrencyDropdownProps) => {
setIsOpen(isOpen) setIsOpen(isOpen)
} }
const changeCurrencyHandler = (currency: string) => { const changeCurrencyHandler = async (newCurrency: string) => {
dispatch({ type: 'currency/setCurrency', payload: currency }) try {
await fetchCurrencyPrice(newCurrency)
} catch (error) {
console.error(error)
}
} }
return ( return (