-
We created a form to add new recipes to our database. Within the form we use another form to add ingredients, that are shown in a list before submitting the form. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi there, in your The reason behind this is most likely that your ingredients state is part of the I would start by moving the ingredients state up to the export default function RecipeForm({ onSubmit, formName, defaultData }) {
const [ingredients, setIngredients] = useState([]);
//...
} I would also move the part of the code where you map over the ingredients to the
//...
<FormularIngredients onSubmit={handleSubmit} />
<StyledIngredientsSection>
<p>added Ingredients:</p>
<ul>
{ingredients.map((ingredient) => {
return (
<li key={ingredient.name}>
{ingredient.name}
{ingredient.amount}
{ingredient.unit}
</li>
);
})}
</ul>
</StyledIngredientsSection> For your Like this: function handleAddIngredient(newIngredient) {
setIngredients([...ingredients, newIngredient]);
} And pass this to your //...
<FormularIngredients onAddIngredient={handleAddIngredient} />
//... Within that component, you need to accept this prop and call the onAddIngredient function whenever //...
<form
onSubmit={(event) => {
event.preventDefault();
onAddIngredient({
/* ingredientId: nanoid(), */
name: event.target.elements.ingredient.value,
amount: event.target.elements.amount.value,
unit: event.target.elements.unit.value,
});
}}
>
..//
Now only one thing is left to do: Update the function handleSubmit(event) {
event.preventDefault();
const formData = new FormData(event.target);
const data = Object.fromEntries(formData);
onSubmit({ ...data, ingredients });
} Hope this already helps 🤞 |
Beta Was this translation helpful? Give feedback.
Hi there,
in your
RecipeForm
you are currently calling the handleSubmit function twice.For the form within this component and also for the form you call in this component (
FormularIngredients
).The reason behind this is most likely that your ingredients state is part of the
FormularIngredients
component but you want to send the data, including the ingredients, whenever theRecipeForm
form is submitted.I would start by moving the ingredients state up to the
RecipeForm
.I would also move the part of the code where you map over the ingredients to the
RecipeForm