JavaScript and React course Β· Module 11: Data Fetching and APIs
Main Project: Cosmic Star Catalog
In this lesson3
You already know every ship system on its own: the transmitter (fetch), the status panel, the race protection, pagination. But on a real mission they all run at once, and bugs show up where the systems meet. Time to combine everything you've learned! In this project you'll build a complete "Cosmic Star Catalog" application that fetches data from an API, handles loading and error states, allows searching and supports pagination.
Project Requirements
Your application should include:
- Fetching data from an API - use
fetch()with async/await - Loading state - display a spinner or skeleton while loading
- Error handling - show an error message with a retry option
- Empty data state - handle the situation when there are no results
- Search - filter results by name with debouncing
- Pagination - navigation between result pages
- Custom hook useFetch - extract the data fetching logic
The only new concept is debouncing: instead of sending a request on every keystroke, we wait until the user stops typing for half a second. Typing the word "Luke" then means one request, not four.
Application Architecture
Before you write code, sketch the ship's modules. Each component has one job, and all the network logic sits in a single hook:
// Component structure:
// App
// βββ SearchBar (search input)
// βββ useFetch (custom hook)
// βββ LoadingSpinner / ErrorMessage / EmptyState
// βββ StarList (results list)
// β βββ StarCard (single result)
// βββ Pagination (page navigation)In our implementation SearchBar and StarList are written directly inside App as an <input> and a grid of cards, for brevity. When the app grows, you'll extract them without changing the logic.
Implementation
We build from the bottom up, starting with the engine. The useFetch hook is the safe fetch from the race conditions lesson, with one addition: a reloadKey counter. It's in the effect's dependencies, so incrementing it through refetch sends the request again to the same address:
import React, { useState, useEffect } from 'react';
// Custom Hook - useFetch
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
if (!url) return;
const controller = new AbortController();
async function fetchData() {
try {
setLoading(true);
setError(null);
const response = await fetch(url, {
signal: controller.signal
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message);
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchData();
return () => controller.abort();
}, [url, reloadKey]);
// Changing reloadKey runs the effect again
const refetch = () => setReloadKey(k => k + 1);
return { data, loading, error, refetch };
}When url changes (a new page or a new search), the cleanup cancels the previous request, so a race can't overwrite the results. Simply setting the same state value, for example setPage(p => p), wouldn't repeat anything, because React skips the render when the state doesn't change. That's why we need a separate counter.
Next come the three status panels from the loading and errors lesson. EmptyState receives the query so it can say what wasn't found:
// Helper components
function LoadingSpinner() {
return (
<div style={{ textAlign: 'center', padding: '40px' }}>
<div className="spinner"></div>
<p>Scanning the galaxy...</p>
</div>
);
}
function ErrorMessage({ message, onRetry }) {
return (
<div className="error-panel">
<h3>Connection lost!</h3>
<p>{message}</p>
<button onClick={onRetry}>Retry scan</button>
</div>
);
}
function EmptyState({ query }) {
return (
<div className="empty-panel">
<p>No results {query ? `for "${query}"` : ''}</p>
<p>Try a different query</p>
</div>
);
}None of these components knows anything about the network, they only receive props. The star card and the pagination are just as simple. Pagination keeps no state of its own, it only reports a page change through onPageChange:
function StarCard({ star }) {
return (
<div className="star-card">
<h3>{star.name}</h3>
<p>Height: {star.height} cm</p>
<p>Mass: {star.mass} kg</p>
<p>Hair color: {star.hair_color}</p>
<p>Birth year: {star.birth_year}</p>
</div>
);
}
function Pagination({ page, totalPages, onPageChange }) {
return (
<div className="pagination">
<button
onClick={() => onPageChange(page - 1)}
disabled={page === 1}
>
Previous
</button>
<span>Page {page} of {totalPages}</span>
<button
onClick={() => onPageChange(page + 1)}
disabled={page >= totalPages}
>
Next
</button>
</div>
);
}The page >= totalPages condition is safer than ===, because it still works when a new search reduces the number of pages.
Finally, the command bridge: App. Debouncing is an effect with setTimeout: every keystroke clears the previous timer, so debouncedQuery changes only after 500 ms of silence. We pass the search text through encodeURIComponent so spaces and special characters don't break the address:
// Main application
function App() {
const [searchQuery, setSearchQuery] = useState('');
const [debouncedQuery, setDebouncedQuery] = useState('');
const [page, setPage] = useState(1);
// Search debounce
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedQuery(searchQuery);
setPage(1); // Reset page on new search
}, 500);
return () => clearTimeout(timer);
}, [searchQuery]);
// Build URL with parameters
const url = debouncedQuery
? `https://swapi.dev/api/people/?search=${encodeURIComponent(debouncedQuery)}&page=${page}`
: `https://swapi.dev/api/people/?page=${page}`;
const { data, loading, error, refetch } = useFetch(url);
const totalPages = data ? Math.ceil(data.count / 10) : 1;
return (
<div className="app">
<h1>Cosmic Star Catalog</h1>
<input
type="text"
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
placeholder="Search the galaxy..."
className="search-input"
/>
{loading && <LoadingSpinner />}
{error && (
<ErrorMessage
message={error}
onRetry={refetch}
/>
)}
{!loading && !error && data && (
<>
{data.results.length === 0 ? (
<EmptyState query={debouncedQuery} />
) : (
<>
<p>Found: {data.count} results</p>
<div className="star-grid">
{data.results.map(star => (
<StarCard key={star.name} star={star} />
))}
</div>
<Pagination
page={page}
totalPages={totalPages}
onPageChange={setPage}
/>
</>
)}
</>
)}
</div>
);
}
export default App;The URL is computed from state on every render rather than stored separately, so it always matches page and debouncedQuery. The "Retry scan" button now calls refetch and really sends the request again. A new search resets the page to 1, because page 3 for "Luke" usually doesn't exist.
This project combines all the techniques from this module: the fetch API, loading/error/empty states, useEffect, the useFetch custom hook, AbortController, debouncing and pagination. Try building it yourself, then compare with the solution above. My advice: start with the hook and a single list, and add search at the end. As an extension, you can swap useFetch for useQuery from TanStack Query and see how much code disappears.
Remember: a good app is a ship in which every module does one thing, and the useFetch hook is its shared communication system.
Code for this lesson: App.jsx
import React, { useState, useEffect } from 'react';
// Custom Hook - useFetch
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
if (!url) {
setLoading(false);
return;
}
const controller = new AbortController();
async function fetchData() {
try {
setLoading(true);
setError(null);
const response = await fetch(url, { signal: controller.signal });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const result = await response.json();
setData(result);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message);
}
} finally {
setLoading(false);
}
}
fetchData();
return () => controller.abort();
}, [url]);
return { data, loading, error };
}
// Helper components
function LoadingSpinner() {
return (
<div className="state-box">
<div className="spinner"></div>
<p>Scanning the galaxy...</p>
</div>
);
}
function ErrorMessage({ message, onRetry }) {
return (
<div className="state-box error-box">
<h3>Connection lost!</h3>
<p>{message}</p>
<button className="retry-btn" onClick={onRetry}>Retry scan</button>
</div>
);
}
function EmptyState({ query }) {
return (
<div className="state-box empty-box">
<h3>Empty sector</h3>
<p>No results found {query ? `for "${query}"` : ''}</p>
</div>
);
}
function StarCard({ star }) {
return (
<div className="star-card">
<h3>{star.name}</h3>
<div className="star-stats">
<div className="stat">
<span className="stat-label">Height</span>
<span className="stat-value">{star.height} cm</span>
</div>
<div className="stat">
<span className="stat-label">Weight</span>
<span className="stat-value">{star.mass} kg</span>
</div>
<div className="stat">
<span className="stat-label">Born</span>
<span className="stat-value">{star.birth_year}</span>
</div>
<div className="stat">
<span className="stat-label">Hair</span>
<span className="stat-value">{star.hair_color}</span>
</div>
</div>
</div>
);
}
function Pagination({ page, totalPages, onPageChange }) {
return (
<div className="pagination">
<button
onClick={() => onPageChange(page - 1)}
disabled={page <= 1}
>
Previous
</button>
<span className="page-info">Page {page} of {totalPages}</span>
<button
onClick={() => onPageChange(page + 1)}
disabled={page >= totalPages}
>
Next
</button>
</div>
);
}
// Main app
function App() {
const [searchQuery, setSearchQuery] = useState('');
const [debouncedQuery, setDebouncedQuery] = useState('');
const [page, setPage] = useState(1);
// Debounce
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedQuery(searchQuery);
setPage(1);
}, 500);
return () => clearTimeout(timer);
}, [searchQuery]);
// URL with parameters
const url = debouncedQuery
? `https://swapi.dev/api/people/?search=${debouncedQuery}&page=${page}`
: `https://swapi.dev/api/people/?page=${page}`;
const { data, loading, error } = useFetch(url);
const totalPages = data ? Math.ceil(data.count / 10) : 1;
return (
<div className="app">
<h1>Cosmic Star Catalog</h1>
<div className="search-bar">
<input
type="text"
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
placeholder="Search the galaxy..."
className="search-input"
/>
</div>
{loading && <LoadingSpinner />}
{error && (
<ErrorMessage
message={error}
onRetry={() => { setPage(1); setDebouncedQuery(debouncedQuery + ' '); }}
/>
)}
{!loading && !error && data && (
<>
{data.results.length === 0 ? (
<EmptyState query={debouncedQuery} />
) : (
<>
<p className="results-count">Found: {data.count} results</p>
<div className="star-grid">
{data.results.map(star => (
<StarCard key={star.name} star={star} />
))}
</div>
{totalPages > 1 && (
<Pagination
page={page}
totalPages={totalPages}
onPageChange={setPage}
/>
)}
</>
)}
</>
)}
</div>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?