I'm trying to change the states in a loop using setTimeout method. I have declared a default state in my constructor like this
constructor(){
super();
this.state = {
postType:'star_rating'
}
}
I want to change the state in 5 seconds which i was able to achieve like this
setTimeout(() => {
this.setState({
postType: 'image_poll'
});
}, 5000);
The problem is after another 5 seconds it should change it to another state. And after another 5 seconds the state change should be repeated from the beginning. So in conclusion the state should change like this
A -> B -> C -> A -> B -> C -> A -> B -> C ....... continuously this should happen. How can i do this?
const states = ['image_poll','star_rating','whatever']; this.currentState = 0; setInterval(() => { this.setState({ if (this.currentState>2) { this.currentState=0; } this.setState({ postType: states[currentState] }) },5000);