Mini-Build: API Data Fetch UI
Build a complete API data fetcher — fetch users from an API, display them, handle loading states, and handle errors. This combines async/await, fetch, DOM manipulation, and error handling.
API Data Fetch Features
- Fetch data — GET request to public API (JSONPlaceholder)
- Loading state — Show 'Loading...' while fetching
- Error state — Show error message if fetch fails
- Display data — Render fetched data as formatted output
- Retry — Allow retrying on failure
- Search/filter — Filter fetched data locally
API Data Fetch Code
// API Data Fetch UI (Logic Only)
class DataFetcher {
constructor(baseURL) {
this.baseURL = baseURL;
this.data = [];
this.loading = false;
this.error = null;
}
async fetchData(endpoint) {
this.loading = true;
this.error = null;
console.log("⏳ Loading...");
try {
const response = await fetch(`${this.baseURL}${endpoint}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
this.data = await response.json();
console.log(`✅ Loaded ${this.data.length} items`);
} catch (error) {
this.error = error.message;
console.error("❌ Error:", error.message);
} finally {
this.loading = false;
}
}
search(query) {
return this.data.filter(item =>
JSON.stringify(item).toLowerCase().includes(query.toLowerCase())
);
}
display(items = this.data) {
if (this.loading) return console.log("⏳ Still loading...");
if (this.error) return console.log(`❌ Error: ${this.error}`);
if (items.length === 0) return console.log("📭 No results");
items.forEach(item => {
console.log(` 👤 ${item.name} — ${item.email} (${item.company?.name || 'N/A'})`);
});
}
}
// Demo usage
const fetcher = new DataFetcher("https://jsonplaceholder.typicode.com");
async function demo() {
// Fetch users
await fetcher.fetchData("/users");
// Display all users
console.log("\n📋 All Users:");
fetcher.display();
// Search
const results = fetcher.search("rom");
console.log(`\n🔍 Search 'rom' (${results.length} results):`);
fetcher.display(results);
// Fetch posts
await fetcher.fetchData("/posts");
console.log(`\n📝 Posts loaded: ${fetcher.data.length}`);
fetcher.display(fetcher.data.slice(0, 3));
}
demo();Tip
Tip
This weather app pattern (fetch + async/await + error handling + DOM updates) is the foundation of every data-driven web app. Master this pattern and you can build any API-powered application.
Fetch does NOT reject on 404/500. Check response.ok.
Common Mistake
Warning
Not caching API responses. Fetching the same data repeatedly wastes bandwidth and hits rate limits. Store responses in a Map or localStorage with timestamps: if (cache[key] && Date.now() - cache[key].time < 300000) return cache[key].data.
Practice Task
Note
Extend the weather app: (1) Add a 5-day forecast feature. (2) Cache responses for 5 minutes. (3) Add geolocation to auto-detect the user's city. (4) Show loading spinner and error states with retry button.
Quick Quiz
Key Takeaways
- Build a complete API data fetcher — fetch users from an API, display them, handle loading states, and handle errors.
- Fetch data — GET request to public API (JSONPlaceholder)
- Loading state — Show 'Loading...' while fetching
- Error state — Show error message if fetch fails