navigation after adding recipes
This commit is contained in:
parent
cd234531b9
commit
e74f247415
3 changed files with 21 additions and 10 deletions
|
@ -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<number | null>(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 name = nameElement.value;
|
||||
const cuisine = cuisineElement.value;
|
||||
await addRecipe(name, cuisine);
|
||||
const recipeData = {
|
||||
name: nameElement.value,
|
||||
cuisine: cuisineElement.value
|
||||
}
|
||||
|
||||
const data = await addRecipe(recipeData);
|
||||
setNewRecipeId(data.id);
|
||||
}
|
||||
|
||||
};
|
||||
React.useEffect(() => {
|
||||
if (newRecipeId !== null) {
|
||||
navigate(`/recipe/${newRecipeId}`);
|
||||
}
|
||||
}, [newRecipeId, navigate]);
|
||||
|
||||
return (
|
||||
<div className="add-recipe-outer">
|
||||
<form onSubmit={addRecipeForm} className="add-recipe-form">
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue