Untitled

 avatar
unknown
plain_text
4 years ago
2.9 kB
3
Indexable
import React, { useEffect, useState } from 'react'
import './App.css'
import CurrencyRow from './CurrencyRow'
import { Nav } from 'react-bootstrap'
import getSymbolFromCurrency from 'currency-symbol-map'

const BASE_URL = 'http://api.exchangeratesapi.io/v1/latest?access_key=80c452bc39093e0011cb59c3135ec8a2'

function App() {
  const [currencyOptions, setCurrencyOptions] = useState([])
  const [fromCurrency, setFromCurrency] = useState()
  const [toCurrency, setToCurrency] = useState()
  const [exchangeRate, setExchangeRate] = useState()
  const [currencySymbol, setCurrencySymbol] = useState()
  const [amount, setAmount] = useState(1)
  const [amountInFromCurrency, setAmountInFromCurrency] = useState(true)

  let toAmount, fromAmount
  if (amountInFromCurrency) {
    fromAmount = amount
    toAmount = amount * exchangeRate
  } else {
    toAmount = amount
    fromAmount = amount / exchangeRate
  }

  useEffect(() => {
    fetch(BASE_URL)
      .then(res => res.json())
      .then(data => {
        const firstCurrency = Object.keys(data.rates)[0]
        setCurrencyOptions([data.base, ...Object.keys(data.rates)])
        setFromCurrency(data.base)
        setCurrencySymbol(data.base)
        getSymbolFromCurrency(currencySymbol)
        setToCurrency(firstCurrency)
        setExchangeRate(data.rates[firstCurrency])
      })
  }, [])
  
  useEffect(() => {
    if (fromCurrency != null && toCurrency != null) {
      console.log(fromCurrency)
      console.log(currencySymbol)
      fetch(`${BASE_URL}&base=${fromCurrency}&symbols=${toCurrency}`)
        .then(res => res.json())
        .then(data => setExchangeRate(data.rates[toCurrency]))
    }
  }, [fromCurrency, toCurrency])

  function handleFromAmountChange(e) {
    setAmount(e.target.value)
    setAmountInFromCurrency(true)
  }

  function handleToAmountChange(e) {
    setAmount(e.target.value)
    setAmountInFromCurrency(false)
  }

  return (
    <>
      <Nav style={{ position: 'absolute', top: '0', width: '100%', backgroundColor: '#79bfda', color: 'white'}}>Navbar</Nav>
    <br />
    <br />
      <h1 style={{ color: '#ebac40'}}>Convert</h1>
      <CurrencyRow
        currencyOptions={currencyOptions}
        selectedCurrency={fromCurrency}
        selectedCurrency={currencySymbol}
        onChangeCurrency={e => setFromCurrency(e.target.value)}
        onChangeAmount={handleFromAmountChange}
        amount={fromAmount}
      />
      <div className="equals">=</div>
      <CurrencyRow
        currencyOptions={currencyOptions}
        selectedCurrency={toCurrency}
        onChangeCurrency={e => setToCurrency(e.target.value)}
        onChangeAmount={handleToAmountChange}
        amount={toAmount}
      />
      <footer style={{ position: 'absolute', bottom: '0', width: '100%', backgroundColor: '#79bfda', color: 'white', padding: '20px' }}>Created by Kevin Choi</footer>
    </>
  )
}

export default App;
Editor is loading...