According to some expert advice from this stackoverflow answer, I attempted to implement a countdown timer for my project as shown 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, upon adding the setState
method in the componentDidUpdate
function, I started encountering the following error:
Invariant Violation: Maximum update depth exceeded
Even though I'm only trying to modify the state within the componentDidMount
when the timer reaches 0, I am puzzled as to why this error is occurring. The code runs once and clears the time interval after setting the state, so I fail to comprehend the reason behind this error message.
If someone could provide an explanation of what I might be doing incorrectly here, I would greatly appreciate it. Thank you.