Created
May 25, 2019 09:55
-
-
Save BertCatsburg/c1164792ffefc62e0939ee547e1b47c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {useState, useEffect} from 'react' | |
import {Dropdown} from 'semantic-ui-react' | |
const coinAPIKey = process.env.REACT_APP_COIN_API_KEY; | |
const CryptoChecker = () => { | |
const [coinName, setCoinName] = useState(null); | |
const useCryptoFetcher = (coinName) => { // Changed: added coinName as a param | |
const [coinData, setCoinData] = useState(null); | |
const [fetched, setFetched] = useState(false); | |
const [loading, setLoading] = useState(false); | |
const coinUrl = `https://rest.coinapi.io/v1/exchangerate/${coinName}/USD`; // Changed: Moved inside the function | |
useEffect(() => { | |
setLoading(true); | |
if (coinName !== null && coinName.length !== 0) { // Changed: Surrounded the fetch with a check on coinName | |
fetch(coinUrl, { | |
headers: { | |
"X-CoinAPI-Key": coinAPIKey | |
} | |
}).then(res => { | |
if (!coinUrl) { | |
setFetched(false); | |
return null | |
} | |
if (!res.ok) { | |
setFetched(false); | |
return null | |
} else { | |
return res.json() | |
} | |
}).then(data => { | |
setLoading(false); | |
setFetched(true); | |
setCoinData(data) | |
} | |
) | |
} else { // Changed: If coinName is nothing we do need to return something for the UI | |
setLoading(false); | |
setFetched(true); | |
setCoinData(null); | |
} | |
}, [coinName, coinUrl]); // Changed: useEffect depends on coinName and coinUrl now. | |
return ([coinData, loading, fetched]) | |
}; | |
const mapCoinData = () => { | |
if (!fetched) return <div>No data fetched</div>; | |
if (loading) return <div>Loading...</div>; | |
if (!coinData) { | |
return <div>No Coin Data</div> | |
} else { | |
return ( | |
<div> | |
<h1>{coinName}</h1> | |
<div>{coinData.rate} USD</div> | |
</div> | |
) | |
} | |
}; | |
const [coinData, loading, fetched] = useCryptoFetcher(coinName); // Changed: Added param coinName | |
const coinOptions = [ | |
{ | |
key: 'BTC', | |
value: 'BTC', | |
text: 'Bitcoin' | |
}, | |
{ | |
key: 'ETH', | |
value: 'ETH', | |
text: 'Ethereum' | |
} | |
]; | |
return ( | |
<div> | |
<Dropdown | |
placeholder='Select Coin' | |
clearable | |
selection | |
options={coinOptions} | |
onChange={ | |
(e, {value}) => { | |
return setCoinName(value); | |
} | |
} | |
/> | |
<br/> | |
{mapCoinData()} | |
</div> | |
) | |
}; | |
export default CryptoChecker; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment