61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
![]() |
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();
|
||
|
console.log(recipes)
|
||
|
console.log("here")
|
||
|
setRecipes(recipes);
|
||
|
} catch (error) {
|
||
|
console.log(error);
|
||
|
setError("Failed to load recipes...");
|
||
|
} finally {
|
||
|
setLoading(false);
|
||
|
}
|
||
|
};
|
||
|
if (shouldFetchRecipes) {
|
||
|
loadRecipes().then(() => setShouldFetchRecipes(false));
|
||
|
}
|
||
|
}, [shouldFetchRecipes]);
|
||
|
|
||
|
const handleDelete = async (id) => {
|
||
|
try {
|
||
|
await deleteRecipe(id);
|
||
|
// Trigger a re-fetch by setting the state variable to true
|
||
|
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;
|