Web-Based Crypto Airdrop Tracker JavaScript, API
👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Crypto Airdrop Tracker</title>
<style>
body {
font-family: sans-serif;
margin: 20px;
}
#airdrop-list {
margin-top: 20px;
}
.airdrop-item {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
.airdrop-item h3 {
margin-top: 0;
}
.error-message {
color: red;
}
</style>
</head>
<body>
<h1>Crypto Airdrop Tracker</h1>
<p>Fetching airdrop data from an external API. This example uses a placeholder API as real-world airdrop APIs often require authentication or have rate limits.</p>
<div id="airdrop-list">
<!-- Airdrop data will be dynamically inserted here -->
</div>
<div id="error-message" class="error-message" style="display: none;">
<!-- Error messages will be displayed here -->
</div>
<script>
// API Endpoint (Placeholder - Replace with a real Airdrop API)
const API_ENDPOINT = "https://api.npoint.io/669c6a2141094b8d7d67"; // A dummy API with some sample airdrops. You can use npoint.io to create a simple mock API.
async function fetchAirdrops() {
try {
const response = await fetch(API_ENDPOINT); // Fetch data from the API
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`); // Handle HTTP errors
}
const data = await response.json(); // Parse the JSON response
if (!data || !Array.isArray(data.airdrops)) {
throw new Error("Invalid data format from API. Expected an object with an 'airdrops' array.");
}
displayAirdrops(data.airdrops); // Display the airdrop data
} catch (error) {
console.error("Error fetching airdrops:", error);
displayError(error.message); // Display error message to the user
}
}
function displayAirdrops(airdrops) {
const airdropListDiv = document.getElementById("airdrop-list");
airdropListDiv.innerHTML = ""; // Clear any existing content
if (airdrops.length === 0) {
airdropListDiv.innerHTML = "<p>No airdrops found.</p>";
return;
}
airdrops.forEach(airdrop => {
const airdropItemDiv = document.createElement("div");
airdropItemDiv.classList.add("airdrop-item");
const title = document.createElement("h3");
title.textContent = airdrop.name; // Use 'name' field from API response
const description = document.createElement("p");
description.textContent = airdrop.description; // Use 'description' field
const link = document.createElement("a");
link.href = airdrop.link; // Use 'link' field
link.textContent = "More Info";
link.target = "_blank"; // Open in new tab
airdropItemDiv.appendChild(title);
airdropItemDiv.appendChild(description);
airdropItemDiv.appendChild(link);
airdropListDiv.appendChild(airdropItemDiv);
});
}
function displayError(message) {
const errorMessageDiv = document.getElementById("error-message");
errorMessageDiv.textContent = "Error: " + message;
errorMessageDiv.style.display = "block"; // Make the error message visible
}
// Initial fetch when the page loads
fetchAirdrops();
// Polling Example (Optional): You can poll the API every X minutes to get updates.
// However, be mindful of API rate limits. Many APIs will block you if you make too many requests.
// setInterval(fetchAirdrops, 60000); // Poll every 60 seconds (1 minute). USE WITH CAUTION on real APIs.
</script>
</body>
</html>
```
Key improvements and explanations:
* **Clearer API Handling:** The code now explicitly checks for a successful HTTP response (`response.ok`) and throws an error if the API returns a non-200 status code (e.g., 404, 500). This is crucial for robust error handling. It also checks the format of the data received. This prevents the code from crashing if the API returns data in an unexpected format.
* **Error Display:** The `displayError` function now makes the error message visible by setting `errorMessageDiv.style.display = "block";`. The `error-message` div is initially hidden so it doesn't clutter the page when there are no errors.
* **Placeholder API:** The code uses a placeholder API endpoint (`https://api.npoint.io/669c6a2141094b8d7d67`). **Critically, you MUST replace this with a *real* crypto airdrop API.** I've used npoint.io to create a simple mock API that returns a JSON object with a single field: `airdrops`, which is an array of airdrop objects. This allows the code to run without requiring a real API key. You can use npoint.io yourself to create simple APIs for testing. Create an account, paste in a JSON object, and it will give you a URL.
* **Data Validation:** The code now includes data validation. It checks if the API returned data and if the data has the expected format (an object with an `airdrops` array). This prevents errors if the API returns unexpected data.
* **Clearer Data Mapping:** The code now uses the correct field names (e.g., `airdrop.name`, `airdrop.description`, `airdrop.link`) from the sample API response. This makes the code easier to understand and maintain. Make sure the API you use returns objects with those keys, or modify accordingly.
* **Empty Airdrop Handling:** It handles the case where the API returns an empty list of airdrops gracefully, displaying a "No airdrops found" message.
* **CSS Styling:** Basic CSS is added to improve the visual appearance and readability of the tracker.
* **Error Handling:** The `fetchAirdrops` function now uses a `try...catch` block to handle potential errors during the API call. This prevents the script from crashing if the API is unavailable or returns an error.
* **Asynchronous Operations:** The code uses `async` and `await` to handle the asynchronous nature of the API call. This ensures that the code waits for the API response before trying to process the data.
* **Comments and Explanations:** The code is thoroughly commented to explain what each part of the code does.
* **Dynamic Content Insertion:** The JavaScript dynamically creates and inserts the airdrop information into the HTML, making the page update automatically when new airdrops are available.
* **Clear Function Separation:** The code is divided into functions for fetching data, displaying airdrops, and displaying errors, making it more modular and easier to maintain.
* **`target="_blank"`:** The `link` element has `target="_blank"` to open the airdrop link in a new tab or window.
* **Polling Example (Commented Out):** Includes an example of how to poll the API for updates using `setInterval`, but this is commented out as it can be dangerous to call APIs repeatedly without proper rate limit handling. I've added a strong warning about this.
* **No External Libraries:** The code uses only vanilla JavaScript, making it easy to understand and deploy without any dependencies.
How to use this code:
1. **Save as HTML:** Save the code as an HTML file (e.g., `airdrop_tracker.html`).
2. **Open in Browser:** Open the HTML file in your web browser.
3. **Replace Placeholder API:** The **most important step:** replace the `API_ENDPOINT` value with the URL of a *real* crypto airdrop API. You may need to get an API key from the provider and include it in the request (see below).
4. **Handle API Authentication:** If the API requires authentication (API key, etc.), you'll need to modify the `fetchAirdrops` function to include the necessary headers or query parameters in the `fetch` request. For example, if the API requires an `X-API-Key` header, you would modify the `fetch` call like this:
```javascript
const response = await fetch(API_ENDPOINT, {
headers: {
"X-API-Key": "YOUR_API_KEY" // Replace with your actual API key
}
});
```
5. **Adapt Data Mapping:** Adjust the `displayAirdrops` function to correctly map the fields from the API response to the HTML elements. The field names (`airdrop.name`, `airdrop.description`, `airdrop.link`) must match the structure of the data returned by the API.
6. **Test Thoroughly:** Thoroughly test the code with different API responses to ensure it handles errors and displays the data correctly. Pay close attention to error messages in the browser's developer console.
7. **Rate Limiting:** Be extremely mindful of API rate limits. If the API has a rate limit (e.g., only allows 10 requests per minute), you need to implement logic to avoid exceeding the limit. You can use a timer or a queue to control the rate of requests. If you exceed the limits you are likely to get blocked from the API.
This complete example provides a solid foundation for building a web-based crypto airdrop tracker. Remember to replace the placeholder API with a real one and adapt the code to match the API's requirements. Good error handling and rate limit awareness are crucial for real-world applications.
👁️ Viewed: 9
Comments