🐣 코드 설명
- 이번 프로젝트에서는 외부 api를 가져와서 환율을 계산하는 방법을 사용했다.
- 기존 강의에서는
fetch
를 사용하는 방법을 알려주었다. axios
라이브러리는 사용해봤는데 fetch
는 처음 사용해보아서 fetch
와 axios
도 정리해보고자 한다.
👩🏻💻 코드
const currencyEl_one = document.getElementById("currency-one");
const amountEl_one = document.getElementById("amount-one");
const currencyEl_two = document.getElementById("currency-two");
const amountEl_two = document.getElementById("amount-two");
const rateEl = document.getElementById("rate");
const swap = document.getElementById("swap");
// Fetch exchange rates and update the DOM
function calculate() {
const currency_one = currencyEl_one.value;
const currency_two = currencyEl_two.value;
fetch(`https://api.exchangerate-api.com/v4/latest/${currency_one}`)
.then((res) => res.json()) // json파일로 변경
.then((data) => {
// console.log(data);
const rate = data.rates[currency_two];
rateEl.innerText = `1 ${currency_one} = ${rate} ${currency_two}`;
amountEl_two.value = (amountEl_one.value * rate).toFixed(2);
});
// axios
// .get(`https://api.exchangerate-api.com/v4/latest/${currency_one}`)
// .then((response) => {
// const rate = response.data.rates[currency_two];
// rateEl.innerText = `1 ${currency_one} = ${rate} ${currency_two}`;
// amountEl_two.value = (amountEl_one.value * rate).toFixed(2);
// });
}
// Event listeners
currencyEl_one.addEventListener("change", calculate);
amountEl_one.addEventListener("input", calculate);
currencyEl_two.addEventListener("change", calculate);
amountEl_two.addEventListener("input", calculate);
swap.addEventListener("click", () => {
const temp = currencyEl_one.value;
currencyEl_one.value = currencyEl_two.value;
currencyEl_two.value = temp;
calculate();
});
calculate();
📃 TIL
✔️ fetch
✔️ axios