import { useParams } from "react-router-dom"; import { useState, useEffect } from "react"; import { getRecipeById } from "../services/frontendApi.js"; import { type Recipe, type Ingredient } from "../types/Recipe" import StarRating from "../components/StarRating.tsx" import { setDBStars } from "../services/frontendApi.js"; function RecipePage() { const [recipe, setRecipe] = useState({ details: {}, ingredients: [], steps: [] }); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const { id } = useParams(); const isWebSource = recipe && recipe.details && recipe.details.author ? /http|com/.test(recipe.details.author) //etc : false; const [stars, setStars] = useState(0); const [initialStars, setInitialStars] = useState(null); useEffect(() => { const loadRecipe = async () => { try { const recipe = await getRecipeById(id); setRecipe(recipe); setStars(recipe.details?.stars ?? 0) setInitialStars(recipe.details?.stars ?? 0); 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]); console.log(recipe) console.log(stars) console.log(initialStars) return (
{error &&
{error}
} {loading ? (
Loading...
) : (

{recipe.details.name}

{recipe.details.cuisine}

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)} />
)}
); } export default RecipePage;