Need a Fresh set of eyes, React Recipe Box Challenge

Hey everyone. I have been racking my brain trying to figure out an issue with my React recipe box. Since I am new to React I am assuming the solution is simple, but I have been staring at my code for far too many hours, and still not getting it. Here is the issue. Load up my pen here:

Click on a recipe to open the accordion, then click edit on the recipe to show the edit modal. Click on the ingredients text area and start adding more ingredients with commas. You will see that the ingredients list behind the modal is being updated in real time. This is not the intended behavior. The recipe list should not update until the user clicks save. The recipe modal and edit recipe function should only be editing a property on the application state called this.state.currentRecipe, but right now it looks like its updating the this.state.recipes (or is it?). For the life of me, I can’t figure out how the wires are getting crossed here. Sorry this is not a straight forward question about a code block, I just can’t see exactly where I am going wrong here.

In this function:

editRecipe(index){
   let currentRecipe = this.state.recipes[index];
   this.setState({
      currentRecipe: currentRecipe,
      currentRecipeIndex: index,
      showModal: true,
      editing: true
   });
}

the assignment on the first line is the problem. The prop this.state.recipes[index] holds an object. When the first line is executed the object is passed by reference to currentRecipe. In a nutshell currentRecipe and this.state.recipes[index] point to the same object. So when you update currentRecipe in handleChange you are actually updating this.state.recipes[index].

On a side note I saw a few places where you pass an object by reference from the state to a variable and then proceed to modify it. This is really bad because you are should update state only through the setState function.

This line in saveRecipes also doesn’t make sence.

this.state.recipes.slice(index, 1, recipeObj);

Thank you, I have been working in javascript for a few months now and it surprises me that I didn’t know about object reference before… Thank you for responding.

If you are still learning React I would suggest you use Create React App. Its friendly for beginners and experts alike. The guide section also covers some very important topics. Also you can use debugging tools like React Developer Tools, which doesn’t seem to work with Codepen.

1 Like

Great, thank you for the recommendation. Checking it out now.