import { useParams, useNavigate, Link } from "react-router-dom"; import { useState, useEffect } from "react"; import { getRecipeById, deleteRecipe, setDBStars } from "../services/frontendApi.js"; import { type Recipe, type Ingredient } from "../types/Recipe" import Modal from '../components/Modal.tsx' import DemoModal from '../components/DemoModal.tsx' import StarRating from "../components/StarRating.tsx" import TimeDisplay from '../components/TimeDisplay.tsx' function RecipePage() { const [recipe, setRecipe] = useState({ details: {}, ingredients: [], steps: [] }); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const [stars, setStars] = useState(0); const [initialStars, setInitialStars] = useState(null); const [showConfirmModal, setShowConfirmModal] = useState(false); const [showDemoModal, setShowDemoModal] = useState(false); const { id } = useParams(); const isWebSource = recipe && recipe.details && recipe.details.author ? /http|com/.test(recipe.details.author) //etc : false; const navigate = useNavigate(); const openModal = () => { setShowConfirmModal(true) }; const closeModal = () => { setShowConfirmModal(false) }; const confirmDelete = () => { if (process.env.NODE_ENV === 'demo') { closeModal(); setShowDemoModal(true); } else { handleDelete(recipe.details.id); closeModal(); } }; useEffect(() => { const loadRecipe = async () => { try { const recipe = await getRecipeById(id); if (!recipe.details) { setError("Sorry, this recipe no longer exists") } else { setRecipe(recipe); setStars(recipe.details?.stars ?? 0) setInitialStars(recipe.details?.stars ?? 0); if (process.env.NODE_ENV === 'dev') { console.log(recipe) } } } catch (error) { console.log(error); setError("Failed to load recipes..."); } finally { setLoading(false); } }; loadRecipe(); }, [id]); useEffect(() => { if (initialStars === null || initialStars === stars) { return; } const updateStarsInDB = async () => { await setDBStars(id, stars); }; updateStarsInDB(); }, [stars]); const handleDelete = async (id: number | void) => { try { await deleteRecipe(id); navigate('/') } catch (error) { console.error("Error deleting recipe:", error); } }; return (
{loading ? (
Loading...
) : error ? (
{error}
Return to Cookbook
) : (

{recipe.details.name}

{recipe.details.cuisine}

prep: | cook:

Ingredients:

    {recipe.ingredients.map((ingredient: Ingredient, index) => (
  • {ingredient.raw}
  • ))}

Instructions:

    {recipe.steps && Object.keys(recipe.steps || {}).map((stepNumber) => (
  1. {recipe.steps[parseInt(stepNumber)].step_number} {recipe.steps[parseInt(stepNumber)].instruction}
  2. ))}
{isWebSource ? ( Source: {recipe.details.author} ) : ( From the kitchen of {recipe.details.author} )} setStars(newRating)} />
) } {showDemoModal && ( setShowDemoModal(false)} closeModal={() => setShowDemoModal(false)} /> )}
); } export default RecipePage;