2

I'm thinking this has something to do with "this", but I can't quite figure it out. I'm receiving an error that title is undefined and states the error stems from my Edit.js file. However, no error displayed until I attempted this.setState({ recipes: updateRecipe});

App.js

constructor() {
  super();
  this.titleChange = this.titleChange.bind(this);
  //get initial state//
  this.state = {
    recipes: {
      recipe1: {
        title: 'Pacific Halibut',
        time: 17,
        description: 'the best halibut ever',
        ingredient: ['halibut', "oil", "salt", "pepper", "kale"],
        instruction: ['preheat oven at 350', 'sprinkle seasonings on fish', 'place foil on baking sheet', 'bake for 17 minutes']
      },
      recipe2: {
        title: 'Cookies',
        time: 12,
        description: 'yummy cookies',
        ingredient: ['cookie dough', 'chocolate chips', 'flour', 'butter', 'sugar'],
        instruction: ['preheat oven at 350', 'mix ingreients together in a bowl', 'place a teaspoon of dough on a baking sheet one inch apart', 'bake for 12 minutes']
      }
    }
  }
}

titleChange = (id) => (e) => {
  const updateRecipe = Object.keys(recipes).map((recipe, sidx) => {
    const target = e.target;
    const name = target.name;
    const value = target.value;
    const recipes = {...this.state.recipes};
    if (id !== sidx) return recipe;
      return { ...recipe, [name]: value};
    });
  console.log(updateRecipe);
  this.setState({ recipes: updateRecipe});
}

Edit.js

render(){
  var id = (this.props.match.params.id);

  return(
    <input type="text" className="add-input" name="title" value={this.props.recipes[id].title} onChange={this.props.titleChange(id)}></input>
}

Thanks for the help.

2
  • can you post your edit component Commented Feb 26, 2018 at 17:41
  • Are you passing all the necessary props to the Edit component? It would be helpful to see the full components. Commented Feb 26, 2018 at 17:43

2 Answers 2

1

In this line you are iterating recipes keys, but recipes itself appears to be undefined at that point:

const updateRecipe = Object.keys(recipes).map((recipe, sidx) => {

Maybe you meant this instead?:

const updateRecipe = Object.keys(this.state.recipes).map((recipe, sidx) => {
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is not related to binding with the correct context, but getting the data from recipes object in

value={this.props.recipes[id].title}

the id that you get from match.params.id may not be present in this.props.recipes and hence it returns undefined, you need to add a check

value={this.props.recipes[id].title? this.props.recipes[id].title: ''}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.