My code is meant to start a timer for 20 minutes -> 20:00. I seem to be missing something in the code. My setState is not changing the value of time when I call it in Timer():
class Sleep extends Component {
// create constructor to get access to props
constructor(props) {
super(props);
this.state = {
time: 1200,
timer: '',
};
}
componentDidMount() {
this.interval = setInterval(this.Timer(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
Timer() {
console.log('time is ' + this.state.time);
this.setState({
time: this.state.time - 1,
});
console.log('time is ' + this.state.time);
var timer;
var minutes = Math.floor(this.state.time / 60);
var seconds = this.state.time % 60;
if (minutes < 10) {
minutes = '0' + minutes.toString();
}
if (seconds < 10) {
seconds = '0' + seconds.toString();
}
timer = minutes.toString() + ':' + seconds.toString();
this.setState({
timer: timer,
});
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#FFFFFF', paddingBottom: 100 }}>
<View>
<Text style={styles.timerText}>{this.state.timer}</Text>
</View>
</View>
);
}
}
The timer should just countdown from 20:00 to 00:00 every second. I threw in some console.log() statements to try and diagnose the issue.