-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
80 lines (64 loc) · 1.99 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
window.onload = () => {
setupEventHandlers();
}
const setupEventHandlers = () => {
const searchButton = document.querySelector('#search-button');
searchButton.addEventListener('click', handleSearchEvent);
}
const handleSearchEvent = () => {
const currency = document.querySelector('#currency-input').value;
const currencyUpperCased = currency.toUpperCase();
cleanList();
if (currency === '') {
showAlert('A moeda deve ser informada');
} else {
// fetchCurrency(currencyUpperCased);
fetchCurrencyAwaitAsync(currencyUpperCased);
}
}
const showAlert = (message) => {
window.alert(message);
}
// const fetchCurrency = (currency) => {
// const endpoint = `https://api.ratesapi.io/api/latest?base=${currency}`;
// fetch(endpoint)
// .then((response) => response.json())
// .then((object) => {
// if (object.error) {
// throw new Error(object.error)
// } else {
// handleRates(object.rates);
// }
// })
// .catch((error) => showAlert(error));
// }
const fetchCurrencyAwaitAsync = async (currency) => {
const endpoint = `https://api.exchangeratesapi.io/v1/latest?access_key=bbcbd7c5841f71a5fbc0e5befde3bc5f`;
try {
const response = await fetch(endpoint);
const object = await response.json();
showAlert("A API mudou, agora não temos no plano free a consulta por 'base' :(...")
if (object.error) {
throw new Error(object.error);
} else {
handleRates(object.rates);
}
} catch (error) {
showAlert(error);
}
}
const handleRates = (rates) => {
const ratesEntries = Object.entries(rates);
// ratesEntries.forEach(renderRate);
ratesEntries.forEach((entry) => renderRate(entry));
}
const renderRate = ([ currency, value ]) => {
const ul = document.querySelector('#currency-list');
const li = document.createElement("li");
li.innerHTML = `${currency}: ${value}`
ul.appendChild(li)
}
const cleanList = () => {
const ul = document.querySelector('#currency-list');
ul.innerHTML = '';
}