0
votes

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
In first example, move authenticate method above ShowLockTimerKrizzu

1 Answers

2
votes

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