[SOLVED] Problem: React Recipe App - index not passed to function

[SOLVED] Problem: React Recipe App - index not passed to function
0

#1

Problem:
Working on the RecipeApp React challenge I encountered a problem with passing the index value of this.state.recipes.map((recipe,index) into function delHandler()

  1. the index variable seems not to be passed at all and is undefined, but why?
  1. if the third element is clicked it deletes the second element instead, is this a problem caused by #1

Codepen:


#2

Problem solved as follows:

  1. using native react index in lists that change dynamically will cause problems, so I added an id property to each element of the object to use as key.
  2. this id is now passed to the delHandler() on click as (e) => this.delHandler(recipe.id)
  3. Instead of relying on the automatically generated index the delHandler now has to find the correct item in the object. The shortest way of doing this seems to be
  delHandler(id) { 
  	let recipesCopy = this.state.recipes.slice()
  	let index = recipesCopy.findIndex(x=>x.id === id)
  	recipesCopy.splice(index,1)
  	this.setState({recipes:recipesCopy})
  }
  1. Additionally there has to be a unique id generated for each new recipe added to the list, so it seems adding a currentId pair to this.state which gets incremented by 1 every time a new recipe item is created should serve well as source for the unique ids