I am working on the react recipe box challenge and have a question regarding setState and forms. In this challenge there are recipes which have both title and ingredients properties. I am representing these recipes as an array of objects in my main component’s state as such:
this.state = {
recipes: [
{
title: "Mac and Cheese",
ingredients: ["Noodles", "Cheese", "Milk"]
},
{
title: "Tofu Stir Fry",
ingredients: ["Veggies", "Soy Sauce", "Tofu"]
}
],
currentRecipe: {}
}
In order to edit an individual recipe I have created another property on the state of the main component called currentRecipe which holds one recipe object which the user has selected to edit. The Form component is then passed props for the main applications this.state.currentRecipe which then populates the forms fields:
<FormControl id="recipe-title" type="text" value={this.props.currentRecipe.title} onChange={this.props.updateCurrentTitle} placeholder="Enter Recipe Name"/>
<FormControl id="recipe-ingredients" componentClass="textarea" placeholder="Enter Ingredients separated by commas..." value={this.props.currentRecipe.ingredients} onChange={this.props.updateCurrentIngredients}>
As you can see I also have created 2 different functions updateCurrentTitle() and updateCurrentIngredients() in order to handle the changes on each of these fields (this is cumbersome, do I really need to make a new function every time I want a field to update?). But here is where the problem comes in, I am representing the currentRecipe as a single object, and I cannot use this.setState() to update only a single property on an object (or can I?). The solution is then to represent each property of the currentRecipe with a different property on the main applications state, but It seems cumbersome to have to represent each part of a recipe with a different property on the main applications state just because this is how react likes to handle changes. So the 2 questions are: do I really need to make a new function for every field to handle changes to that field? and 2: is it possible to use this.setState() to update only a property on an object?