From e74f2474155c486cb64cef5a8aad9f69186cdd92 Mon Sep 17 00:00:00 2001 From: fred <> Date: Tue, 8 Jul 2025 11:13:01 -0700 Subject: [PATCH] navigation after adding recipes --- frontend/src/pages/AddRecipe.tsx | 22 ++++++++++++++++++---- frontend/src/pages/Cookbook.tsx | 5 +---- frontend/src/services/backend.js | 4 ++-- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/frontend/src/pages/AddRecipe.tsx b/frontend/src/pages/AddRecipe.tsx index 784a21a..cd25298 100644 --- a/frontend/src/pages/AddRecipe.tsx +++ b/frontend/src/pages/AddRecipe.tsx @@ -1,19 +1,33 @@ +import React, { useState } from 'react'; import { addRecipe } from "../services/backend.js"; +import { useNavigate } from "react-router-dom"; function AddRecipe() { + const [newRecipeId, setNewRecipeId] = useState(null); + const navigate = useNavigate(); + const addRecipeForm = async (event: React.FormEvent) => { event.preventDefault(); const nameElement = document.getElementById('ar-name') as HTMLInputElement | null; const cuisineElement = document.getElementById('ar-cuisine') as HTMLInputElement | null; if (nameElement && cuisineElement) { + const recipeData = { + name: nameElement.value, + cuisine: cuisineElement.value + } - const name = nameElement.value; - const cuisine = cuisineElement.value; - await addRecipe(name, cuisine); + const data = await addRecipe(recipeData); + setNewRecipeId(data.id); } - } + }; + React.useEffect(() => { + if (newRecipeId !== null) { + navigate(`/recipe/${newRecipeId}`); + } + }, [newRecipeId, navigate]); + return (
diff --git a/frontend/src/pages/Cookbook.tsx b/frontend/src/pages/Cookbook.tsx index 7738f64..365d934 100644 --- a/frontend/src/pages/Cookbook.tsx +++ b/frontend/src/pages/Cookbook.tsx @@ -13,8 +13,6 @@ function Cookbook() { const loadRecipes = async () => { try { const recipes = await getRecipes(); - console.log(recipes) - console.log("here") setRecipes(recipes); } catch (error) { console.log(error); @@ -28,10 +26,9 @@ function Cookbook() { } }, [shouldFetchRecipes]); - const handleDelete = async (id) => { + const handleDelete = async (id: number | void) => { try { await deleteRecipe(id); - // Trigger a re-fetch by setting the state variable to true setShouldFetchRecipes(true); } catch (error) { console.error("Error deleting recipe:", error); diff --git a/frontend/src/services/backend.js b/frontend/src/services/backend.js index 3d38158..949edec 100644 --- a/frontend/src/services/backend.js +++ b/frontend/src/services/backend.js @@ -10,11 +10,11 @@ export const getRecipeById = async (id) => { return data; }; -export const addRecipe = async (name, cuisine) => { +export const addRecipe = async (recipeData) => { const response = await fetch("http://localhost:6063/add-recipe", { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name, cuisine }) + body: JSON.stringify(recipeData) }); const data = await response.json(); console.log(data)