There are a few issues with the code you have provided:
The fetch function used to send the API request is asynchronous, which means that the code after the fetch call will be executed before the request is completed. This means that the data variable will not have been assigned a value when it is used to extract the result property. To fix this, you should move the code that uses the data variable inside the then block of the fetch function, like this:
const response = await fetch(
`https://api.fastforex.io/convert?from=${fromCurrency}&to=${toCurrency}&amount=${amount}&api_key=xxxxxxxxxxx`
);
response.json().then((data) => {
const result = data.result;
resultElement.innerText = `${amount} ${fromCurrency} is equal to ${result} ${toCurrency}`;
});
The fetch function can throw an exception if there is an error with the request, such as a network error or a problem with the API server. To handle these exceptions, you should wrap the fetch call in a try-catch block.
The Failed to fetch error you are seeing in the console may be caused by a problem with the URL you are using to send the request. Make sure that the URL is correct and that the API key you are using is valid.
Here is the revised code with these changes applied:
const form = document.getElementById("conversion-form");
const amountInput = document.getElementById("amount");
const fromCurrencyInput = document.getElementById("from-currency");
const toCurrencyInput = document.getElementById("to-currency");
const resultElement = document.getElementById("result");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const amount = amountInput.value;
const fromCurrency = fromCurrencyInput.value;
const toCurrency = toCurrencyInput.value;
try {
const response = await fetch(
`https:
);
response.json().then((data) => {
const result = data.result;
resultElement.innerText = `${amount} ${fromCurrency} is equal to ${result} ${toCurrency}`;
});
} catch (error) {
console.error(error);
resultElement.innerText = "An error occurred. Please try again later.";
}
});