Upon running following statement it's showing this following error in the console tab
Command Running in the Console convert(100, 'CAD', 'USD')
Error showing in the console after running the above conversion statment request
`Paused on promise rejecion TypeError: Cannot read properties of undefined
At the line of code 64
here
const rate = ratesByBase[from].rates[to];`
Folllowing is my full code base
let currencies = {
AUD: 'Australian Dollar',
BGN: 'Bulgarian Lev',
BRL: 'Brazilian Real',
CAD: 'Canadian Dollar',
CHF: 'Swiss Franc',
CNY: 'Chinese Yuan',
CZK: 'Czech Republic Koruna',
DKK: 'Danish Krone',
GBP: 'British Pound Sterling',
HKD: 'Hong Kong Dollar',
HRK: 'Croatian Kuna',
HUF: 'Hungarian Forint',
IDR: 'Indonesian Rupiah',
ILS: 'Israeli New Sheqel',
INR: 'Indian Rupee',
JPY: 'Japanese Yen',
KRW: 'South Korean Won',
MXN: 'Mexican Peso',
MYR: 'Malaysian Ringgit'
}
const fromSelect = document.querySelector('[name="from_currency"]');
const toSelect = document.querySelector('[name="to_currency"]');
const fromInput = document.querySelector('[name="from_amount"]');
let myHeaders = new Headers();
myHeaders.append("apikey", "QC9I9O0LPCFUfStGMD1h5CKcWN4Aehrk");
let requestOptions = {
method: 'GET',
redirect: 'follow',
headers: myHeaders
};
const endpoint = "https://api.apilayer.com/currency_data/live";
let ratesByBase = {};
function generateOptions(options) {
return Object.entries(options)
.map(([currencyCode, currencyName]) =>
`<option value="${currencyCode}">${currencyCode} - ${currencyName}</option>`)
.join("");
}
async function fetchRates(base = "USD") {
const res = await fetch(`${endpoint}?base=${base}`, requestOptions);
const rates = await res.json();
return rates;
}
async function convert(amount, from, to) {
// first check if we even have the rates to convert from that currency
if (!ratesByBase[from]) {
console.log(`Oh no! we don't have ${from} to convert it ${to}, so let 's go get it`);
const rates = await fetchRates(from);
console.log(rates);
// store them for next time
ratesByBase[from] = rates;
}
const rate = ratesByBase[from].rates[to];
const convertedAmount = rate * amount;
console.log('${amount} ${from} is ${convertedAmount} in ${to}');
return convertedAmount;
}
const optionsHTML = generateOptions(currencies);
// populate the options elements
fromSelect.innerHTML = optionsHTML;
toSelect.innerHTML = optionsHTML;