Lesson 7 of 8
Mini Project: GitHub Repository Explorer
Build a GitHub repository explorer using the public GitHub API: search repos with TanStack Query, infinite scroll for results, star repo mutation with optimistic update, rate limit error handling, and request cancellation on every keystroke.
GitHub Explorer Implementation
import { useState, useEffect, useRef } from 'react';
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query';
// ---- GitHub API types ----
interface GHRepo {
id: number;
full_name: string;
description: string | null;
stargazers_count: number;
language: string | null;
html_url: string;
updated_at: string;
forks_count: number;
open_issues_count: number;
}
// ---- API functions ----
async function searchRepos(query: string, page: number, signal?: AbortSignal): Promise<{ items: GHRepo[]; total: number }> {
if (!query) return { items: [], total: 0 };
const url = `https://api.github.com/search/repositories?q=${encodeURIComponent(query)}&per_page=10&page=${page}&sort=stars`;
const response = await fetch(url, {
signal,
headers: { Accept: 'application/vnd.github.v3+json' },
});
if (response.status === 403) throw new Error('Rate limit exceeded. Please wait a minute.');
if (!response.ok) throw new Error(`GitHub API error: ${response.status}`);
return response.json();
}
// ---- Debounce hook ----
function useDebounce<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const t = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(t);
}, [value, delay]);
return debounced;
}
// ---- Repo card ----
function RepoCard({ repo }: { repo: GHRepo }) {
return (
<a
href={repo.html_url}
target="_blank"
rel="noopener noreferrer"
style={{ display: 'block', background: '#1e293b', borderRadius: 10, padding: 16, textDecoration: 'none', color: 'inherit', border: '1px solid #334155', transition: 'border-color 0.2s' }}
onMouseEnter={e => (e.currentTarget.style.borderColor = '#229c6b')}
onMouseLeave={e => (e.currentTarget.style.borderColor = '#334155')}
>
<h3 style={{ margin: '0 0 6px', fontSize: 15, color: '#60a5fa' }}>{repo.full_name}</h3>
<p style={{ margin: '0 0 12px', fontSize: 13, color: '#94a3b8', lineClamp: 2 }}>
{repo.description ?? 'No description'}
</p>
<div style={{ display: 'flex', gap: 16, fontSize: 12, color: '#64748b' }}>
{repo.language && <span>โ {repo.language}</span>}
<span>โญ {repo.stargazers_count.toLocaleString()}</span>
<span>๐ด {repo.forks_count.toLocaleString()}</span>
<span>๐ {repo.open_issues_count.toLocaleString()}</span>
</div>
</a>
);
}
// ---- Main App ----
export default function GitHubExplorer() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 400);
const loadMoreRef = useRef<HTMLDivElement>(null);
const {
data,
isLoading,
isError,
error,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['github', 'repos', debouncedQuery],
queryFn: ({ pageParam = 1, signal }) => searchRepos(debouncedQuery, pageParam as number, signal),
initialPageParam: 1,
getNextPageParam: (lastPage, allPages) =>
lastPage.items.length === 10 ? allPages.length + 1 : undefined,
enabled: debouncedQuery.length >= 2, // only search if query is at least 2 chars
staleTime: 5 * 60 * 1000,
});
const repos = data?.pages.flatMap(p => p.items) ?? [];
const totalCount = data?.pages[0]?.total ?? 0;
// Intersection Observer for infinite scroll
useEffect(() => {
const observer = new IntersectionObserver(
entries => { if (entries[0].isIntersecting && hasNextPage && !isFetchingNextPage) fetchNextPage(); },
{ threshold: 0.5 }
);
const el = loadMoreRef.current;
if (el) observer.observe(el);
return () => observer.disconnect();
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
return (
<div style={{ fontFamily: 'system-ui', background: '#0f172a', minHeight: '100vh', color: 'white', padding: 24, maxWidth: 720, margin: '0 auto' }}>
<h1 style={{ margin: '0 0 4px', fontSize: 26 }}>๐ GitHub Explorer</h1>
<p style={{ margin: '0 0 20px', color: '#64748b', fontSize: 13 }}>Search GitHub repositories using the public API</p>
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search repositories (e.g. react, zustand, next.js)..."
autoFocus
style={{ width: '100%', background: '#1e293b', border: '1px solid #334155', color: 'white', padding: '12px 16px', borderRadius: 10, fontSize: 15, boxSizing: 'border-box' }}
/>
{debouncedQuery.length >= 2 && (
<p style={{ color: '#64748b', fontSize: 13, margin: '8px 0 16px' }}>
{isLoading ? 'Searching...' : `${totalCount.toLocaleString()} results for "${debouncedQuery}"`}
</p>
)}
{isError && (
<div style={{ background: '#450a0a', border: '1px solid #991b1b', borderRadius: 8, padding: '12px 16px', marginBottom: 16, color: '#fca5a5', fontSize: 13 }}>
โ ๏ธ {(error as Error).message}
</div>
)}
{isLoading && (
<div style={{ display: 'grid', gap: 12 }}>
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} style={{ background: '#1e293b', borderRadius: 10, padding: 16, height: 100, animation: 'pulse 1.5s infinite', border: '1px solid #334155' }} />
))}
</div>
)}
<div style={{ display: 'grid', gap: 12 }}>
{repos.map(repo => <RepoCard key={repo.id} repo={repo} />)}
</div>
{/* Infinite scroll sentinel */}
<div ref={loadMoreRef} style={{ height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{isFetchingNextPage && <span style={{ color: '#64748b', fontSize: 13 }}>Loading more...</span>}
{!hasNextPage && repos.length > 0 && <span style={{ color: '#334155', fontSize: 13 }}>- End of results -</span>}
</div>
{!debouncedQuery && (
<div style={{ textAlign: 'center', marginTop: 60, color: '#334155' }}>
<p style={{ fontSize: 40 }}>๐</p>
<p>Type at least 2 characters to search</p>
</div>
)}
</div>
);
}What This Project Demonstrates
- useInfiniteQuery - cursor-based (page number) infinite pagination with GitHub's search API
- Intersection Observer for infinite scroll - load-more triggered automatically when sentinel element enters viewport
- Request cancellation - TanStack Query automatically cancels previous requests when query key (debouncedQuery) changes
- Debounced search - 400ms delay prevents an API call on every keystroke
- Rate limit error handling - GitHub's 403 rate-limit response translated to user-friendly message
- Conditional `enabled` - query only runs when query length >= 2 to avoid empty searches
- Stale time - 5 minute cache means repeated searches for the same query don't hit the API
Tip
Tip
Practice Mini Project GitHub Repository Explorer in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Mini Project: GitHub Repository Explorer
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project GitHub Repository Explorer from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Mini Project GitHub Repository Explorer is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- Build a GitHub repository explorer using the public GitHub API: search repos with TanStack Query, infinite scroll for results, star repo mutation with optimistic update, rate limit error handling, and request cancellation on every keystroke.
- useInfiniteQuery - cursor-based (page number) infinite pagination with GitHub's search API
- Intersection Observer for infinite scroll - load-more triggered automatically when sentinel element enters viewport
- Request cancellation - TanStack Query automatically cancels previous requests when query key (debouncedQuery) changes
Finished this lesson?