From c66d5800cccfd9a7875e338295f9ce426597f987 Mon Sep 17 00:00:00 2001 From: Kyle Zarazan Date: Thu, 21 Nov 2024 22:08:47 -0700 Subject: [PATCH] fix delete button on update --- .../components/recipes/RecipeEdit.tsx | 2 +- .../components/recipes/RecipeForm.tsx | 26 ++++++++++++++++--- .../components/recipes/RecipeNew.tsx | 8 +----- app/javascript/types/types.ts | 3 ++- app/models/recipe.rb | 2 +- 5 files changed, 27 insertions(+), 14 deletions(-) diff --git a/app/javascript/components/recipes/RecipeEdit.tsx b/app/javascript/components/recipes/RecipeEdit.tsx index dd33dc0..1475f7c 100644 --- a/app/javascript/components/recipes/RecipeEdit.tsx +++ b/app/javascript/components/recipes/RecipeEdit.tsx @@ -1,7 +1,7 @@ import React, { useEffect, useState } from 'react'; import { useAppDispatch, useAppSelector } from '../../store/hooks'; import { updateRecipe } from '../../store/recipesSlice'; -import { RecipeFormData } from './RecipeNew'; +import { RecipeFormData } from './RecipeForm'; import useCsrfToken from '../../hooks/useCsrfToken'; import { useNavigate, useParams } from 'react-router-dom'; import RecipeForm from './RecipeForm'; diff --git a/app/javascript/components/recipes/RecipeForm.tsx b/app/javascript/components/recipes/RecipeForm.tsx index f71c618..b3d027f 100644 --- a/app/javascript/components/recipes/RecipeForm.tsx +++ b/app/javascript/components/recipes/RecipeForm.tsx @@ -1,6 +1,12 @@ import React from 'react'; -import { RecipeFormData } from './RecipeNew'; import { useAppSelector } from '../../store/hooks'; +import { Ingredient } from '../../types/types'; + +export interface RecipeFormData { + name: string; + description: string; + ingredients_attributes: Ingredient[]; +} interface RecipeFormProps { formData: RecipeFormData; @@ -25,13 +31,26 @@ const RecipeForm: React.FC = ({ formData, setFormData, onSubmit const deleteIngredient = (indexToDelete: number) => { setFormData({ ...formData, - ingredients_attributes: formData.ingredients_attributes.filter((_, index) => index !== indexToDelete) + ingredients_attributes: formData.ingredients_attributes + .map((ingredient, index) => { + if (index === indexToDelete) { + if (ingredient.id) { + return { ...ingredient, _destroy: true }; + } + return null; + } + return ingredient; + }) + .filter((ingredient): ingredient is Ingredient => + ingredient !== null + ) }); }; const handleIngredientChange = (index: number, field: 'food_id' | 'measurement', value: string | number) => { const newIngredients = [...formData.ingredients_attributes]; newIngredients[index] = { + id: newIngredients[index]?.id || undefined, food_id: newIngredients[index]?.food_id || 0, measurement: newIngredients[index]?.measurement || '', [field]: value @@ -66,7 +85,7 @@ const RecipeForm: React.FC = ({ formData, setFormData, onSubmit

Ingredients

{formData.ingredients_attributes.map((ingredient, index) => ( -
+