2025-07-08 10:40:49 -07:00
|
|
|
import CookbookRecipeTile from "../components/CookbookRecipeTile.tsx"
|
|
|
|
import { useState, useEffect } from "react";
|
|
|
|
import { getRecipes, deleteRecipe } from "../services/backend.js";
|
|
|
|
import { type Recipe } from "../types/Recipe"
|
|
|
|
|
|
|
|
function Cookbook() {
|
|
|
|
const [recipes, setRecipes] = useState([]);
|
|
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const loadRecipes = async () => {
|
|
|
|
try {
|
|
|
|
const recipes = await getRecipes();
|
|
|
|
setRecipes(recipes);
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error);
|
|
|
|
setError("Failed to load recipes...");
|
|
|
|
} finally {
|
|
|
|
setLoading(false);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if (shouldFetchRecipes) {
|
|
|
|
loadRecipes().then(() => setShouldFetchRecipes(false));
|
|
|
|
}
|
|
|
|
}, [shouldFetchRecipes]);
|
|
|
|
|
2025-07-08 11:13:01 -07:00
|
|
|
const handleDelete = async (id: number | void) => {
|
2025-07-08 10:40:49 -07:00
|
|
|
try {
|
|
|
|
await deleteRecipe(id);
|
|
|
|
setShouldFetchRecipes(true);
|
|
|
|
} catch (error) {
|
|
|
|
console.error("Error deleting recipe:", error);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div className="home">
|
|
|
|
|
|
|
|
{error && <div className="error-message">{error}</div>}
|
|
|
|
|
|
|
|
{loading ? (
|
|
|
|
<div className="loading">Loading...</div>
|
|
|
|
) : (
|
|
|
|
<div className="recipes-grid">
|
|
|
|
{recipes.map((recipe: Recipe) => (
|
|
|
|
<CookbookRecipeTile recipe={recipe} key={recipe.id} handleDelete={handleDelete} />
|
|
|
|
))}
|
|
|
|
</div>
|
|
|
|
)}
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Cookbook;
|