0

I am trying to learn how to code in react and I am following a tutorial. I've encountered a problem (Which I solved in another way) but would like to know how it works.

I have the following function before my render(){} method:

onDeleteHandler = () => {
  axios.delete('my_firebase_link'+this.props.obj.id+'.json')
  .then(console.log('Deleted'))
  .catch(err => console.log(err))

}

And in my render method, I tried to dynamically create a table row

render() {      
let tabRow = <p>Hello</p>;
if(this.state.businesses){
  tabRow = this.state.businesses.map(function(object, i){
    return <TableRow obj={object} key={i} onDelete={this.onDeleteHandler}/>;
  });
} return();

However, when I try to run that code, I get the following error: TypeError: Cannot read property 'onDeleteHandler' of undefined

After some searching for some tutorials, I ended up with the following code which works perfectly

render() {      
let tabRow = <p>Hello</p>;
if(this.state.businesses){
  tabRow = this.state.businesses.map(element =>(
    <TableRow obj={element} key={element.id} onDelete={(id) => this.onDeleteHandler(element.id)}/>
  ))
} return();

I would like to know why the last solution works, and why is it when I use the "function()" method inside the map, it throws an error.

Sorry if my explanation might be confusing but I will give any code if my explanation lacks it.

Thank you so much!

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Lorenzo
  • 574
  • 5
  • 13
  • https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/ - point #1 – Jayce444 Oct 09 '20 at 12:49
  • See top part of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Andre Nuechter Oct 09 '20 at 12:50
  • 1
    In the first case, ```this``` was not bound to the original component, hence it was undefined. You could have bind it in the constructor. In the second example, the arrow function automatically binds ```this``` so it works fine. – szczocik Oct 09 '20 at 12:50
  • I'm sorry, It looks like my code also had some flaws when I pasted it here having been trying to solve it so long. I'll take a look more into your answers and thank you very much for your help – Lorenzo Oct 09 '20 at 13:24

0 Answers0