move navigation behavior for editor to methods

This commit is contained in:
Anika Raemer 2025-09-07 10:33:15 +02:00
parent 0eec7cf58e
commit 5c8ddf96f2
2 changed files with 26 additions and 10 deletions

View file

@ -1,6 +1,6 @@
import { useParams, useNavigate } from "react-router-dom"
//import { useEffect, useState } from "react"
//import type { Recipe } from "../types/recipe"
import type { Recipe } from "../types/recipe"
import RecipeEditor from "./RecipeEditor"
import { recipes } from "../mock_data/recipes"
@ -48,13 +48,29 @@ export default function RecipeEditView() {
}
if (!recipe) return <div>Loading...</div>
*/
const handleSave = () => {
console.log("Saving")
navigate("/") // back to list
const handleSave = (updatedRecipe : Recipe) => {
console.log("Saving", updatedRecipe.title)
navigateBack();
}
const handleCancel = () => {
console.log("Cancelling edit mode for", recipe ? recipe.id : "no recipe at all")
navigateBack();
}
const navigateBack = () => {
if(recipe && recipe.id){
console.log("navigating to recipe with id", recipe.id)
navigate("/recipe/" + recipe.id) // go back to detail view
} else {
console.log("navigating back to list as no recipe was selected")
navigate("/") // no recipe -> go back to list
}
}
// error handling -> if there is no recipe, we cannot open edit view
if (!recipe) return <div>Oops, there's no recipe in RecipeEditView</div>
console.log("opening recipe in edit mode", recipe.title, id)
return <RecipeEditor recipe={recipe} onSave={handleSave} />
return <RecipeEditor recipe={recipe} onSave={handleSave} onCancel={handleCancel}/>
}

View file

@ -1,5 +1,4 @@
import { useState } from "react"
import { Link } from "react-router-dom" // @todo replace cancel link with button and onCancel handler
import type { Recipe } from "../types/recipe"
import type { Ingredient } from "../types/ingredient"
import {IngredientListEditor} from "./IngredientListEditor"
@ -7,13 +6,14 @@ import {IngredientListEditor} from "./IngredientListEditor"
type RecipeEditorProps = {
recipe: Recipe
onSave: (recipe: Recipe) => void
onCancel: () => void
}
/**
* Editor component for managing a recipe, including title,
* ingredients (with amount, unit, name), instructions, and image URL.
*/
export default function RecipeEditor({ recipe, onSave }: RecipeEditorProps) {
export default function RecipeEditor({ recipe, onSave, onCancel }: RecipeEditorProps) {
const [draft, setDraft] = useState<Recipe>(recipe)
const updateIngredients = (ingredients: Ingredient[]) => {
@ -58,12 +58,12 @@ export default function RecipeEditor({ recipe, onSave }: RecipeEditorProps) {
>
Save
</button>
<Link
to={`/recipe/${recipe.id}`}
<button
className="default-button"
onClick={() => onCancel()}
>
Cancel
</Link>
</button>
</div>
</div>
)