renaming, restructuring, adding an api util to the frontend (currently editPage only and a mock backend
This commit is contained in:
parent
1bd1952ecb
commit
38a5707622
16 changed files with 247 additions and 117 deletions
76
frontend/src/components/recipes/RecipeEditPage.tsx
Normal file
76
frontend/src/components/recipes/RecipeEditPage.tsx
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { useParams, useNavigate } from "react-router-dom"
|
||||
import { useEffect, useState } from "react"
|
||||
import type { Recipe } from "../../types/recipe"
|
||||
import RecipeEditor from "./RecipeEditor"
|
||||
import { fetchRecipe, createRecipe, updateRecipe } from "../../api/recipePoint"
|
||||
|
||||
export default function RecipeEditPage() {
|
||||
const { id } = useParams<{ id: string }>()
|
||||
const [recipe, setRecipe] = useState<Recipe | null>(null)
|
||||
const navigate = useNavigate()
|
||||
|
||||
useEffect(() => {
|
||||
const loadRecipe = async () => {
|
||||
if (id) {
|
||||
try {
|
||||
// Fetch recipe data when editing an existing one
|
||||
const data = await fetchRecipe(id)
|
||||
setRecipe(data)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
} else {
|
||||
// New recipe case
|
||||
setRecipe({
|
||||
id: "",
|
||||
title: "",
|
||||
ingredientGroupList: [
|
||||
],
|
||||
instructions: "",
|
||||
servings: {
|
||||
amount: 1,
|
||||
unit: ""
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
loadRecipe()
|
||||
}, [id])
|
||||
|
||||
const handleSave = async (updated: Recipe) => {
|
||||
try {
|
||||
if (updated.id) {
|
||||
await updateRecipe(updated)
|
||||
} else {
|
||||
await createRecipe(updated)
|
||||
}
|
||||
navigateBack();
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
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>Loading...</div>
|
||||
}
|
||||
|
||||
return <RecipeEditor recipe={recipe} onSave={handleSave} onCancel={handleCancel}/>
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue