Xavier C. Xavier C. - 6 months ago 292
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) {
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");
}


}

Answer

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)

Comments