interface ExchangeRates {
[key: string]: number;
}
interface ApiResponse {
rates: ExchangeRates;
}
document.addEventListener("DOMContentLoaded", function () {
const amountInput = document.getElementById("amount") as HTMLInputElement;
const fromCurSelect = document.getElementById("fromCur") as HTMLSelectElement;
const toCurSelect = document.getElementById("toCur") as HTMLSelectElement;
const resultParagraph = document.getElementById(
"result",
) as HTMLParagraphElement;
async function convert(): Promise<void> {
const amount = Number(amountInput.value);
const fromCur = fromCurSelect.value;
const toCur = toCurSelect.value;
if (fromCur === toCur) {
resultParagraph.textContent = `${amount} ${toCur}`;
return;
}
try {
resultParagraph.textContent = "Loading...";
const res = await fetch(
`https://api.frankfurter.app/latest?amount=${amount}&from=${fromCur}&to=${toCur}`,
);
if (!res.ok) throw new Error("Error fetching data");
const data: ApiResponse = await res.json();
resultParagraph.textContent = `${data.rates[toCur]} ${toCur}`;
} catch (error) {
console.error("Failed to fetch data:", error);
resultParagraph.textContent = "Error";
}
}
amountInput.addEventListener("input", convert);
fromCurSelect.addEventListener("change", convert);
toCurSelect.addEventListener("change", convert);
convert();
});