Xavier C. Xavier C. - 1 year ago 482
Javascript Question

setState Is not Working Inside setInterval In React

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) {

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 style={styles.buttonsWrapper}>
<Button buttonType='startStop' onPress={this._handlePressStartStop}>Start</Button>
<Button buttonType='lap' onPress={this._handlePressLap}>Lap</Button>
<View style={styles.footer}>

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

let startTime = new Date();

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


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



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)