Last active
March 28, 2023 17:25
-
-
Save marko-knoebl/8dfff642f5beb7a39f497278edd3cb7e to your computer and use it in GitHub Desktop.
fetch demo: exchange rates
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Exchange Rates</title> | |
</head> | |
<body> | |
<div class="main"> | |
<h1>exchange rates</h1> | |
<div>from: USD</div> | |
<div> | |
to: | |
<select class="to-dropdown"></select> | |
</div> | |
<div class="exchangerate-display"></div> | |
</div> | |
<script src="index.js" defer></script> | |
</body> | |
</html> |
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
const BASE_URL = | |
"https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/"; | |
const CURRENCIES = ["eur", "jpy", "gbp", "rub"]; | |
const exchangeRateDisplay = document.querySelector(".exchangerate-display"); | |
const toDropdown = document.querySelector(".to-dropdown"); | |
async function loadExchangeRate(from, to) { | |
const url = BASE_URL + `${from}/${to}.json`; | |
const res = await fetch( | |
// URL | |
url, | |
// Configuration | |
{ | |
// optional | |
method: "GET", | |
headers: {}, | |
// not needed in this case | |
body: null, | |
} | |
); | |
if (!res.ok) { | |
// status is e.g. 404, 400, 500, ... | |
console.log("Error while fetching"); | |
throw new Error("Error while fetching"); | |
} | |
// read the response body as json | |
const data = await res.json(); | |
document.querySelector(".exchangerate-display").innerText = data[to]; | |
} | |
/** | |
* include options in the dropdown menu | |
*/ | |
function populateDropdown() { | |
toDropdown.innerHTML = CURRENCIES.map( | |
(currency) => | |
`<option value="${currency}">${currency.toUpperCase()}</option>` | |
).join(); | |
toDropdown.addEventListener("input", (e) => { | |
const newValue = e.target.value; | |
loadExchangeRate("usd", newValue); | |
}); | |
} | |
populateDropdown(); | |
loadExchangeRate("usd", CURRENCIES[0]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment