Hey guys, I have been working on this problem for a solid week now and I am getting nowhere.
What happens is that I have an onClick event that triggers a function that is setup inside the parent element and for whatever reason when I call on the function(click the button) it tells me this ‘_this2.deleteRecipe’ is undefined.
Here is the code I am working with. Thanks so much for helping me. Many of the functions are not set up in any way, but once I get deleteRecipe working the other functions will follow its pattern.
if (localStorage.getItem("elliott_recipes")) {
var recipeList = JSON.parse(localStorage.getItem("elliott_recipes"));
} else {
var recipeList = [{
id: 1,
recipeName: "Apple Pie",
ingredients: "apple,dough"
}, {
id: 2,
recipeName: "Lemon Pie",
ingredients: "lemon,dough"
}, ];
}
class Recipe extends React.Component{
constructor(props) {
super(props);
this.state = {
recipes: recipeList,
addRecipe: function() {
alert("hello");
updateChanges(this.state.recipeList());
},
editRecipe: function(key) {
alert("hello");
updateChanges(this.state.recipeList());
}
deleteRecipe: function(id) {
for (var j = 0; j < this.recipes.length; j++) {
if (this.recipes[j].id == id) {
this.recipes.splice(j, 1);
}
}
updateChanges(recipeList);
console.log(recipeList);
}
}
}
//this is were the onClick issues come from.
render() {
var dispList = [];
this.state.recipes.forEach(function (item, i) {
console.log();
dispList.push(<div key={"key_"+ i}><h3>Recipe: {item.recipeName} - <button onClick={() =>{this.state.editRecipe(item.id)}}>Edit</button> <button onClick={() =>{this.state.deleteRecipe(item.id)}}>Delete</button></h3><p>Ingredients: {item.ingredients}</p><br /></div>);
})
return (
<div>
{dispList}
<button onClick={() =>{this.addRecipe()}}>Add Recipe</button>
</div>
)
}
};
ReactDOM.render(<Recipe />, document.getElementById('content'));
function updateChanges(y) {
localStorage.setItem("elliott_recipes", JSON.stringify(y));
}
I am new to React and so it is totally a possibility that I am missing something really simple here.