Syntax Question for Creating Data (video 5) in Calling Backend Services (section 8)

@02:45

I’m confused about these two different syntaxes.

class App extends Component {
async componentDidMount() {

}
handleAdd = async () => {

};
}

Moshes explanation “componentDidMount is just a method in this class. But handleAdd is a property that we’re setting to a function.”

Why two different syntaxes, aren’t both methods, except one is an arrow function?

Thank you!

You can use arrow function style in ‘componentDidMount’ as well. The difference between method and arrow function is ‘this’ when passing into a callback function. I highly recommend you to read arrow funcion document in mdn.

1 Like

Thanks for your reply.
So in this case I assume we can use regular funcs for the handlers or arrow funcs?
That’s were I got confused, I don’t see why he mixed arrow and regular funcs, because there’s no closure (as far as I can tell). “this” in all methods is referencing the same object.

Because handleAdd method will pass into the click handler. If you were familiar with the events(onClick, etc) in Javascript, you will know if you just passed a normal function into that, the context will be (this = context) where it called, but not the ‘class App’ where it should be. Then ‘this.xxx’ will be undefined. You need arrow function to bind ‘this’ context to ‘class App’. However, the componentDidMount just be called as a class method, use either style does not change the context. If you still confused what I said, I think you maybe need to make some efforts on Object Oriented JS.

https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc

1 Like

Thanks Haku. Much appreciated!!! :+1:

Moshes detailed explanation of the concept:

Section 3:
Video 10 (Handling Events)
Video 11 (Binding Event Handlers)