feat(frontend): implement recipe list page with search and pagination

- Create API client service (src/services/api.ts) with all CRUD operations
- Create useRecipes hook for data fetching with search and pagination
- Create RecipeCard component for displaying individual recipes
- Implement RecipeListPage with search bar, empty state, and error handling
- Add grid layout with responsive design (1-3 columns)
- Implement 'Load More' button for pagination
- Add recipe metadata display (servings, time, last cooked)
- Update TODO.md to mark task as complete
This commit is contained in:
Paul Huliganga 2026-03-24 03:12:27 -04:00
parent 94c061a850
commit c6c5d0e3f4
5 changed files with 471 additions and 11 deletions

12
TODO.md
View File

@ -19,7 +19,7 @@
- [x] Initialize React + Vite project
- [x] Configure Tailwind CSS
- [x] Set up React Router
- [ ] Create recipe list page
- [x] Create recipe list page
- [ ] Create recipe detail/edit page
- [ ] Implement cook mode UI
@ -46,6 +46,16 @@
## ✅ Completed Tasks
### 2026-03-24
- **Recipe list page implementation**
- Created API client service (src/services/api.ts) with all CRUD operations
- Created useRecipes hook for data fetching with search and pagination
- Created RecipeCard component for displaying individual recipes
- Implemented RecipeListPage with search bar, empty state, loading state, error handling
- Added grid layout with responsive design (1-3 columns)
- Implemented "Load More" button for pagination
- Added recipe count display and meta information (servings, time, last cooked)
- Verified TypeScript compilation and Vite build succeed
- **React Router setup**
- Updated main.tsx to wrap App in BrowserRouter
- Configured routes in App.tsx with navigation header

View File

@ -0,0 +1,87 @@
/**
* RecipeCard - Displays a single recipe in the list view
*/
import { Link } from 'react-router-dom';
import type { Recipe } from '../types/recipe';
interface RecipeCardProps {
recipe: Recipe;
}
/**
* Format time in minutes to readable string
*/
function formatTime(minutes?: number): string {
if (!minutes) return '';
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
}
/**
* Format date timestamp to readable string
*/
function formatDate(timestamp?: number): string {
if (!timestamp) return '';
const date = new Date(timestamp * 1000);
return date.toLocaleDateString();
}
export function RecipeCard({ recipe }: RecipeCardProps) {
const totalTime = (recipe.prep_time_minutes || 0) + (recipe.cook_time_minutes || 0);
return (
<Link
to={`/recipe/${recipe.id}`}
className="block bg-white rounded-lg shadow hover:shadow-md transition-shadow border border-gray-200"
>
<div className="p-5">
{/* Title */}
<h3 className="text-lg font-semibold text-gray-900 mb-2 line-clamp-2">
{recipe.title}
</h3>
{/* Description */}
{recipe.description && (
<p className="text-sm text-gray-600 mb-3 line-clamp-2">
{recipe.description}
</p>
)}
{/* Meta information */}
<div className="flex flex-wrap gap-3 text-xs text-gray-500">
{recipe.servings && (
<div className="flex items-center gap-1">
<span>🍽</span>
<span>{recipe.servings} servings</span>
</div>
)}
{totalTime > 0 && (
<div className="flex items-center gap-1">
<span></span>
<span>{formatTime(totalTime)}</span>
</div>
)}
{recipe.last_cooked_at && (
<div className="flex items-center gap-1">
<span>👨🍳</span>
<span>Last cooked {formatDate(recipe.last_cooked_at)}</span>
</div>
)}
</div>
{/* Footer with ingredient count */}
<div className="mt-4 pt-3 border-t border-gray-100">
<div className="flex justify-between items-center text-xs text-gray-500">
<span>{recipe.ingredients.length} ingredients</span>
<span className="text-blue-600 font-medium">View Recipe </span>
</div>
</div>
</div>
</Link>
);
}

View File

@ -0,0 +1,90 @@
/**
* Hook for fetching and managing recipes
*/
import { useState, useEffect } from 'react';
import { fetchRecipes } from '../services/api';
import type { Recipe } from '../types/recipe';
interface UseRecipesOptions {
search?: string;
limit?: number;
}
interface UseRecipesResult {
recipes: Recipe[];
loading: boolean;
error: string | null;
hasMore: boolean;
loadMore: () => void;
refresh: () => void;
}
/**
* Hook to fetch recipes with search and pagination
*/
export function useRecipes(options: UseRecipesOptions = {}): UseRecipesResult {
const { search = '', limit = 20 } = options;
const [recipes, setRecipes] = useState<Recipe[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [offset, setOffset] = useState(0);
const [hasMore, setHasMore] = useState(true);
const loadRecipes = async (currentOffset: number, append: boolean = false) => {
setLoading(true);
setError(null);
try {
const data = await fetchRecipes({
search: search || undefined,
offset: currentOffset,
limit,
});
if (append) {
setRecipes(prev => [...prev, ...data]);
} else {
setRecipes(data);
}
// If we got fewer recipes than requested, we've reached the end
setHasMore(data.length === limit);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load recipes');
setRecipes([]);
} finally {
setLoading(false);
}
};
// Load recipes when search term changes
useEffect(() => {
setOffset(0);
setHasMore(true);
loadRecipes(0, false);
}, [search]);
const loadMore = () => {
if (!loading && hasMore) {
const newOffset = offset + limit;
setOffset(newOffset);
loadRecipes(newOffset, true);
}
};
const refresh = () => {
setOffset(0);
setHasMore(true);
loadRecipes(0, false);
};
return {
recipes,
loading,
error,
hasMore,
loadMore,
refresh,
};
}

View File

@ -1,21 +1,154 @@
/**
* RecipeListPage - Displays a list of all recipes with search and filtering
*/
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { useRecipes } from '../hooks/useRecipes';
import { RecipeCard } from '../components/RecipeCard';
export function RecipeListPage() {
const [searchTerm, setSearchTerm] = useState('');
const [searchQuery, setSearchQuery] = useState('');
const { recipes, loading, error, hasMore, loadMore } = useRecipes({
search: searchQuery,
limit: 20,
});
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
setSearchQuery(searchTerm);
};
const handleClearSearch = () => {
setSearchTerm('');
setSearchQuery('');
};
return (
<div>
{/* Header */}
<div className="mb-6">
<div className="flex justify-between items-center mb-4">
<div>
<h2 className="text-2xl font-bold text-gray-900">My Recipes</h2>
<p className="mt-1 text-sm text-gray-500">
Browse and search your recipe collection
</p>
</div>
<Link
to="/recipe/new"
className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium transition-colors"
>
+ New Recipe
</Link>
</div>
<div className="bg-white rounded-lg shadow p-6">
<p className="text-gray-600">
Recipe list will be implemented here (next task)
{/* Search Bar */}
<form onSubmit={handleSearch} className="flex gap-2">
<div className="flex-1 relative">
<input
type="text"
placeholder="Search recipes by title or ingredients..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
{searchQuery && (
<button
type="button"
onClick={handleClearSearch}
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
aria-label="Clear search"
>
</button>
)}
</div>
<button
type="submit"
className="px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors"
>
Search
</button>
</form>
{searchQuery && (
<p className="mt-2 text-sm text-gray-600">
Searching for: <span className="font-medium">"{searchQuery}"</span>
</p>
)}
</div>
{/* Error State */}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
<p className="text-red-800">
<strong>Error:</strong> {error}
</p>
</div>
)}
{/* Loading State (first load) */}
{loading && recipes.length === 0 && (
<div className="text-center py-12">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
<p className="mt-4 text-gray-600">Loading recipes...</p>
</div>
)}
{/* Empty State */}
{!loading && !error && recipes.length === 0 && (
<div className="bg-white rounded-lg shadow p-12 text-center">
<div className="text-6xl mb-4">🍳</div>
<h3 className="text-xl font-semibold text-gray-900 mb-2">
{searchQuery ? 'No recipes found' : 'No recipes yet'}
</h3>
<p className="text-gray-600 mb-6">
{searchQuery
? 'Try a different search term'
: 'Get started by adding your first recipe'}
</p>
{!searchQuery && (
<Link
to="/recipe/new"
className="inline-block bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-medium transition-colors"
>
Add Your First Recipe
</Link>
)}
</div>
)}
{/* Recipe Grid */}
{recipes.length > 0 && (
<>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{recipes.map((recipe) => (
<RecipeCard key={recipe.id} recipe={recipe} />
))}
</div>
{/* Load More Button */}
{hasMore && (
<div className="mt-8 text-center">
<button
onClick={loadMore}
disabled={loading}
className="px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? 'Loading...' : 'Load More'}
</button>
</div>
)}
{/* Results summary */}
<div className="mt-6 text-center text-sm text-gray-500">
Showing {recipes.length} recipe{recipes.length !== 1 ? 's' : ''}
</div>
</>
)}
</div>
);
}

View File

@ -0,0 +1,140 @@
/**
* API client for Recipe Manager backend
*/
import type { Recipe, Tag, ApiResponse } from '../types/recipe';
const API_BASE_URL = 'http://localhost:3000/api';
/**
* Fetch recipes with optional filters
*/
export async function fetchRecipes(params?: {
search?: string;
offset?: number;
limit?: number;
}): Promise<Recipe[]> {
const url = new URL(`${API_BASE_URL}/recipes`);
if (params?.search) {
url.searchParams.set('search', params.search);
}
if (params?.offset !== undefined) {
url.searchParams.set('offset', params.offset.toString());
}
if (params?.limit !== undefined) {
url.searchParams.set('limit', params.limit.toString());
}
const response = await fetch(url.toString());
if (!response.ok) {
throw new Error(`Failed to fetch recipes: ${response.statusText}`);
}
const result: ApiResponse<Recipe[]> = await response.json();
if (!result.success || !result.data) {
throw new Error(result.error || 'Failed to fetch recipes');
}
return result.data;
}
/**
* Fetch a single recipe by ID
*/
export async function fetchRecipe(id: number): Promise<Recipe> {
const response = await fetch(`${API_BASE_URL}/recipes/${id}`);
if (!response.ok) {
throw new Error(`Failed to fetch recipe: ${response.statusText}`);
}
const result: ApiResponse<Recipe> = await response.json();
if (!result.success || !result.data) {
throw new Error(result.error || 'Failed to fetch recipe');
}
return result.data;
}
/**
* Create a new recipe
*/
export async function createRecipe(recipe: Omit<Recipe, 'id' | 'created_at' | 'updated_at' | 'last_cooked_at'>): Promise<Recipe> {
const response = await fetch(`${API_BASE_URL}/recipes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(recipe),
});
if (!response.ok) {
throw new Error(`Failed to create recipe: ${response.statusText}`);
}
const result: ApiResponse<Recipe> = await response.json();
if (!result.success || !result.data) {
throw new Error(result.error || 'Failed to create recipe');
}
return result.data;
}
/**
* Update a recipe
*/
export async function updateRecipe(id: number, updates: Partial<Omit<Recipe, 'id' | 'created_at' | 'updated_at'>>): Promise<Recipe> {
const response = await fetch(`${API_BASE_URL}/recipes/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
});
if (!response.ok) {
throw new Error(`Failed to update recipe: ${response.statusText}`);
}
const result: ApiResponse<Recipe> = await response.json();
if (!result.success || !result.data) {
throw new Error(result.error || 'Failed to update recipe');
}
return result.data;
}
/**
* Delete a recipe
*/
export async function deleteRecipe(id: number): Promise<void> {
const response = await fetch(`${API_BASE_URL}/recipes/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`Failed to delete recipe: ${response.statusText}`);
}
const result: ApiResponse<{ deleted: number }> = await response.json();
if (!result.success) {
throw new Error(result.error || 'Failed to delete recipe');
}
}
/**
* Fetch all tags
*/
export async function fetchTags(): Promise<Tag[]> {
const response = await fetch(`${API_BASE_URL}/tags`);
if (!response.ok) {
throw new Error(`Failed to fetch tags: ${response.statusText}`);
}
const result: ApiResponse<Tag[]> = await response.json();
if (!result.success || !result.data) {
throw new Error(result.error || 'Failed to fetch tags');
}
return result.data;
}