2020-05-22 14:38:19 +02:00
|
|
|
import React, { useState, useEffect, ReactElement } from 'react'
|
2019-11-23 21:53:33 +01:00
|
|
|
import fetch from 'node-fetch'
|
2021-03-14 01:34:04 +01:00
|
|
|
import { conversion as styleConversion } from './Conversion.module.css'
|
2018-10-14 20:28:35 +02:00
|
|
|
|
2020-05-22 14:38:19 +02:00
|
|
|
export async function getFiat(
|
|
|
|
amount: number
|
|
|
|
): Promise<{ [key: string]: string }> {
|
2020-03-07 18:22:12 +01:00
|
|
|
const url =
|
|
|
|
'https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=eur%2Cusd'
|
2019-11-22 21:26:50 +01:00
|
|
|
const response = await fetch(url)
|
2020-03-07 18:22:12 +01:00
|
|
|
|
2019-11-22 21:26:50 +01:00
|
|
|
if (!response.ok) console.error(response.statusText)
|
|
|
|
const data = await response.json()
|
2020-03-07 18:22:12 +01:00
|
|
|
const { usd, eur } = data.ethereum
|
|
|
|
const dollar = (amount * usd).toFixed(2)
|
|
|
|
const euro = (amount * eur).toFixed(2)
|
2018-10-14 20:28:35 +02:00
|
|
|
|
2019-11-22 21:26:50 +01:00
|
|
|
return { dollar, euro }
|
|
|
|
}
|
2019-01-01 19:32:49 +01:00
|
|
|
|
2020-05-22 14:38:19 +02:00
|
|
|
export default function Conversion({
|
|
|
|
amount
|
|
|
|
}: {
|
2021-03-23 21:38:06 +01:00
|
|
|
amount: string
|
2020-05-22 14:38:19 +02:00
|
|
|
}): ReactElement {
|
2019-11-22 21:26:50 +01:00
|
|
|
const [conversion, setConversion] = useState({
|
|
|
|
euro: '0.00',
|
|
|
|
dollar: '0.00'
|
|
|
|
})
|
|
|
|
const { dollar, euro } = conversion
|
2018-10-14 20:28:35 +02:00
|
|
|
|
2019-11-22 21:26:50 +01:00
|
|
|
async function getFiatResponse() {
|
2019-10-23 13:09:26 +02:00
|
|
|
try {
|
2021-03-23 21:38:06 +01:00
|
|
|
const { dollar, euro } = await getFiat(Number(amount))
|
2019-11-22 21:26:50 +01:00
|
|
|
setConversion({ euro, dollar })
|
2019-10-23 13:09:26 +02:00
|
|
|
} catch (error) {
|
2019-11-21 21:32:55 +01:00
|
|
|
console.error(error.message)
|
2019-10-23 13:09:26 +02:00
|
|
|
}
|
2018-10-14 20:28:35 +02:00
|
|
|
}
|
|
|
|
|
2019-11-22 21:26:50 +01:00
|
|
|
useEffect(() => {
|
|
|
|
getFiatResponse()
|
|
|
|
}, [amount])
|
2019-10-23 13:09:26 +02:00
|
|
|
|
2019-11-22 21:26:50 +01:00
|
|
|
return (
|
2021-03-14 01:34:04 +01:00
|
|
|
<div className={styleConversion}>
|
2019-11-22 21:26:50 +01:00
|
|
|
<span>{dollar !== '0.00' && `= $ ${dollar}`}</span>
|
|
|
|
<span>{euro !== '0.00' && `= € ${euro}`}</span>
|
|
|
|
</div>
|
|
|
|
)
|
2018-10-14 20:28:35 +02:00
|
|
|
}
|