As this stackoverflow answer says, I tried to create a countdown timer for my project like below.
constructor(props: Object) {
super(props);
this.state ={ timer: 3,hideTimer:false}
}
componentDidMount(){
this.interval = setInterval(
() => this.setState({timer: --this.state.timer}),
1000
);
}
componentDidUpdate(){
if(this.state.timer === 0){
clearInterval(this.interval);
this.setState({hideTimer:true})
}
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', }}>
<Text> {this.state.timer} </Text>
</View>
)
}
However after adding setState into componentDidUpdate
function, I stated to get below error,
Invariant Violation: Maximum update depth exceeded
Since I'm only trying to get state under componentDidMount
if and only if time equals to 0, I don' understand why I get above error because that code only execute only once and after state set, timeinterval get clear as well.
So can someone explain please what I'm doing wrong here? Thank you.