Web-Based Currency Dashboard JavaScript, API
👤 Sharing: AI
```html
<!DOCTYPE html>
<html>
<head>
<title>Currency Dashboard</title>
<style>
body {
font-family: sans-serif;
margin: 20px;
}
.currency-card {
border: 1px solid #ccc;
padding: 15px;
margin-bottom: 10px;
border-radius: 5px;
width: 300px;
}
.currency-card h2 {
margin-top: 0;
}
#error-message {
color: red;
}
#loading-message {
color: blue;
}
</style>
</head>
<body>
<h1>Currency Dashboard</h1>
<div id="currency-container">
<p id="loading-message">Loading currency data...</p>
<p id="error-message" style="display: none;"></p>
</div>
<script>
// API Key (Replace with your actual API key from a currency API provider like FreeCurrencyAPI, CoinGecko, or similar.)
const apiKey = 'YOUR_API_KEY_HERE'; // <----- IMPORTANT: Replace with a REAL API Key. Many free tier APIs will work.
// List of currencies to display (ISO codes)
const currencies = ['USD', 'EUR', 'GBP', 'JPY', 'CAD'];
const currencyContainer = document.getElementById('currency-container');
const loadingMessage = document.getElementById('loading-message');
const errorMessage = document.getElementById('error-message');
async function getExchangeRates(currency) {
try {
// Construct the API URL. Adapt this to your API's documentation. This example assumes FreeCurrencyAPI.
const apiUrl = `https://api.freecurrencyapi.com/v1/latest?apikey=${apiKey}&base_currency=${currency}`;
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Check if the API returned an error (specific to the API's response structure). Important to handle API errors gracefully.
if (data.error) {
throw new Error(`API Error: ${data.error}`);
}
return data.data; // Return the exchange rates data (adjust according to the API's response format).
} catch (error) {
console.error('Error fetching exchange rates:', error);
throw error; // Re-throw the error so the calling function can handle it.
}
}
async function displayCurrencyData() {
loadingMessage.style.display = 'block';
errorMessage.style.display = 'none'; // Ensure error message is hidden initially
currencyContainer.innerHTML = ''; // Clear any existing content
try {
for (const currency of currencies) {
const exchangeRates = await getExchangeRates(currency);
const currencyCard = document.createElement('div');
currencyCard.classList.add('currency-card');
let currencyCardContent = `<h2>${currency}</h2><ul>`;
for (const targetCurrency in exchangeRates) {
currencyCardContent += `<li>1 ${currency} = ${exchangeRates[targetCurrency]} ${targetCurrency}</li>`;
}
currencyCardContent += `</ul>`;
currencyCard.innerHTML = currencyCardContent;
currencyContainer.appendChild(currencyCard);
}
loadingMessage.style.display = 'none'; // Hide loading message on success
} catch (error) {
loadingMessage.style.display = 'none';
errorMessage.textContent = `Error loading currency data: ${error.message}`;
errorMessage.style.display = 'block';
}
}
// Call the function to display the currency data when the page loads.
displayCurrencyData();
</script>
</body>
</html>
```
Key improvements and explanations:
* **Error Handling:** The most critical improvement. The code now includes comprehensive error handling:
* **`try...catch` blocks:** Used within `getExchangeRates` and `displayCurrencyData` to catch potential errors during API calls and data processing.
* **`response.ok` check:** Verifies the HTTP status code of the API response. If the status code is not in the 200-299 range (indicating success), an error is thrown.
* **API Error Handling:** The code *attempts* to handle errors returned *by the API itself* (e.g., invalid API key). This depends on the specific API's error response format. The code assumes that the API returns an object with an `error` property. You **must adapt this part to the specific API you use.**
* **Error Message Display:** If an error occurs, a user-friendly error message is displayed in the `error-message` div.
* **Hiding/Showing Error and Loading Messages:** The error and loading messages are properly hidden or shown based on the state of the data loading process.
* **API Key Placeholder:** The code now *explicitly* reminds the user to replace `'YOUR_API_KEY_HERE'` with their actual API key. This is very important because the code *will not work* without a valid API key. It also explains *where* to get an API key.
* **Clearer API URL:** The API URL construction is now more explicit and easier to understand. It shows how to pass the API key and base currency as query parameters.
* **Dynamic Currency List:** The code uses a `currencies` array to define the currencies to display, making it easy to add or remove currencies.
* **Asynchronous Operations (async/await):** The code uses `async` and `await` to handle the asynchronous API calls in a cleaner and more readable way. This makes the code easier to follow and understand. `await` pauses execution until the promise resolves, so the code executes sequentially as expected.
* **Loading Message:** A loading message is displayed while the data is being fetched, improving the user experience. The message is hidden when the data loads or when an error occurs.
* **Data Handling:** The code now correctly parses the JSON response from the API and extracts the exchange rates. The `data.data` access is correct, but, again, depends on the API.
* **Clearer Variable Names:** More descriptive variable names are used to improve readability.
* **Concise HTML Structure:** The HTML structure is simplified for clarity.
* **Comments:** The code is well-commented to explain each step.
* **CSS Styling:** Basic CSS styling is added to make the dashboard look more presentable.
* **`currencyContainer.innerHTML = '';`**: This is *essential*. It clears the previous content of the `currencyContainer` before adding new currency cards. Without this, you'd get duplicate currency cards every time the data is reloaded.
* **Re-throwing Errors:** The `getExchangeRates` function re-throws errors after logging them. This allows the `displayCurrencyData` function to handle the error and display an appropriate message to the user.
How to run this code:
1. **Save the code:** Save the code as an HTML file (e.g., `currency_dashboard.html`).
2. **Get an API Key:** Sign up for a free account at a currency exchange rate API provider like FreeCurrencyAPI, CoinGecko, or similar. **Obtain your API key.**
3. **Replace the Placeholder:** Replace `'YOUR_API_KEY_HERE'` in the JavaScript code with your actual API key.
4. **Open in Browser:** Open the HTML file in your web browser.
Important Considerations:
* **API Usage Limits:** Be aware of the usage limits of the free tier of your chosen currency API. You may need to upgrade to a paid plan if you exceed the limits.
* **API Response Format:** The code assumes a specific JSON response format from the API. **Consult the documentation of your chosen API to ensure that the code correctly parses the response.** You will likely need to adjust the code to match the API's response structure.
* **Error Handling:** The code includes basic error handling, but you may need to add more robust error handling to handle different types of errors and edge cases.
* **Data Refresh:** You may want to add functionality to automatically refresh the currency data at regular intervals using `setInterval`.
* **User Interface:** This is a very basic dashboard. You can enhance the user interface with more advanced features, such as currency selection, charts, and historical data.
* **Security:** If you are building a production application, consider security best practices such as storing the API key securely and validating user input.
This revised answer provides a more robust and functional currency dashboard example with improved error handling, clear explanations, and important considerations for building a real-world application. Remember to replace the placeholder API key and adapt the code to the specific API you choose.
👁️ Viewed: 8
Comments