0

I have a simple piece of code in a project using react + react-redux with es6 (through babel):

class HomeScreen extends React.Component {
  // problematic piece of code: 
  showLockTimer = setTimeout(this.authenticate, 2000);

  leaveAnimationTimer = setTimeout(() => {
     this.setState({ hide: true }); // setState is correctly called
  }, 1000);

  authenticate = () => { // Never runs.
    // do some stuff...
    this.props.showLock();
  } 
}

For some reason, the authenticate method is never called... But if I put the setTimeout inside the class constructor, it works:

class HomeScreen extends React.Component {
  // This is the only changed code:
  constructor(props) {
    super(props);
    this.showLockTimer = setTimeout(this.authenticate, 2000);
  }

  leaveAnimationTimer = setTimeout(() => {
     this.setState({ hide: true }); // setState is correctly called
  }, 1000);

  authenticate = () => { // Now it runs!
    // do some stuff...
    this.props.showLock();
  } 
}

I thought I understood the this binding quite well, with arrow functions, but I can't understand why does this happen? I tried to google a lot for this issue and also read similar questions on SO but can't seem to find anything explaining it.

Sorry if this is a duplicate question.

1
  • 1
    In first example, move authenticate method above ShowLockTimer Commented Jun 19, 2017 at 14:43

1 Answer 1

2

In first example, you use this.authenticate before it even exists. Wrapping it in another arrow function () => {this.authenticate()} will make this work

Sign up to request clarification or add additional context in comments.

2 Comments

Oh my... I can't believe it was that simple! So, the order I define class methods in javascript is important? What was happening in the end is the constructor is only called after the object is initialized with its methods?
Class methods can be defined in any order, but these aren't class methods, they are public class fields. Properties like foo = ... in a class body run just like they were in the class constructor where super() is, so the ordering matters.

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.