3

When I click on my button that is calling the _handlePressStartStop() function, I get an error about setState. It tells :

 **(intermediate value).bind is not a function**

I know I've got trouble with this, maybe it the source of my problem. Here is my code:

class StopWatch extends Component {

constructor(props) {
  super(props);

  this.state = {
    startTime: null,
    timeElapsed: null
  };
}

render() {
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <View style={styles.counter}>
          <Text style={styles.counterText}>{this.state.timeElapsed}</Text>
        </View>
        <View style={styles.buttonsWrapper}>
          <Button buttonType='startStop' onPress={this._handlePressStartStop}>Start</Button>
          <Button buttonType='lap' onPress={this._handlePressLap}>Lap</Button>
        </View>
      </View>
      <View style={styles.footer}>
      </View>
    </View>
  )
}

_handlePressStartStop() {
  console.log("press start");

  let startTime = new Date();

  setInterval(() => {
      this.setState({
        timeElapsed: new Date() - startTime
      }.bind(this))
  }, 1000);

}

_handlePressLap() {
  console.log("press lap");
}

}

Auguste
  • 2,007
  • 2
  • 17
  • 25
Xavier C.
  • 1,809
  • 4
  • 24
  • 40
  • Objects don't have a `.bind` method. That's what the error is telling you. `{...}.bind(this)` is simply invalid. – Felix Kling May 24 '16 at 18:07
  • Related: [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling May 24 '16 at 18:09

2 Answers2

3

you wouldnt want to bind to this like that. You're binding the object to this which is invalid. How about you bind the handler

onPress={this._handlePressStartStop}.bind(this) instead?

this way, everything executed inside the handler function will have the same this (a react component instance)

nuway
  • 2,324
  • 4
  • 27
  • 48
0

Try this._handlePressStartStop.bind(this)

Nader Dabit
  • 52,483
  • 13
  • 107
  • 91