Load and save recipes from backend

This commit is contained in:
Anika Raemer 2025-09-12 19:25:50 +02:00
parent 38a5707622
commit 568606213d
5 changed files with 102 additions and 16 deletions

View file

@ -1,7 +1,7 @@
import { useParams, Link } from "react-router-dom"
import { recipes } from "../../mock_data/recipes"
import type { Recipe } from "../../types/recipe"
import { useState } from "react"
import { useEffect, useState } from "react"
import { fetchRecipe } from "../../api/recipePoint"
/**
@ -11,22 +11,43 @@ import { useState } from "react"
export default function RecipeDetailPage() {
// Extract recipe ID from route params
const { id } = useParams<{ id: string }>()
const recipe = recipes.find((r) => r.id === id)
// the recipe loaded from the backend, don't change this! it's required for scaling
const [recipe, setRecipe] = useState<Recipe | null>(null)
// Working copy for re-calculating ingredients
const [recipeWorkingCopy, setRecipeWorkingCopy] = useState<Recipe|null>(null)
// load recipe data whenever id changes
useEffect(() => {
const loadRecipe = async () => {
if (id) {
try {
// Fetch recipe data when editing an existing one
console.log("loading recipe with id", id)
const data = await fetchRecipe(id)
setRecipe(data)
} catch (err) {
console.error(err)
}
}
}
loadRecipe()
}, [id])
// set original recipe data and working copy when recipe changes
useEffect( ()=> {
setRecipeWorkingCopy(recipe);
}, [recipe])
if (!recipe) {
if (!recipe || !recipeWorkingCopy) {
return <p className="p-6">Recipe not found.</p>
}
// Working copy for re-calculating ingredients
const [recipeWorkingCopy, updateRecipeWorkingCopy] = useState<Recipe>(recipe)
// Keep original immutable for scaling
const [originalRecipe] = useState<Recipe>(recipe)
/** recalculate ingredients based on the amount of servings */
const recalculateIngredients = (newAmount: number) => {
// Always calculate factor from the *original recipe*, not the working copy
const factor = newAmount / originalRecipe.servings.amount
const factor = newAmount / recipe.servings.amount
// Create a new ingredient list with updated amounts
const updatedIngredientGroupList = recipe.ingredientGroupList.map((ingGrp) => ({
@ -38,7 +59,7 @@ export default function RecipeDetailPage() {
}))
// Update working copy with new servings + recalculated ingredients
updateRecipeWorkingCopy({
setRecipeWorkingCopy({
...recipeWorkingCopy,
servings: {
...recipeWorkingCopy.servings,