Why there're no bindings in the project walkthrough codes of the Social Network for Pets for the methods?

second step in the task Social Network for Pets
and here’s the Project Walkthrough

May anybody please explain why there were no this bindings involved for the method loadUserData in the project walkthrough video?

Hi @code4379867815
in the lesson linked you call the loadUserData method twice in the lifecycle methods componentDidMount and componentDidUpdate. You do not pass it to an event handler inside the render method. That’s when you would need this binding.
From the react docs:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick , this will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick} , you should bind that method.

You also find an explanation in the Codecademy lesson Call this.setState from Another Function

Due to the way that event handlers are bound in JavaScript, this.toggleMood() loses its this when it is used on line 20. Therefore, the expressions this.state.mood and this.setState on lines 7 and 8 won’t mean what they’re supposed to… unless you have already bound the correct this to this.toggleMood .

1 Like