Reputation: 7105
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?
Upvotes: 1
Views: 5069
Reputation: 26034
That's just a simple state machine. This is one possible implementation:
setTimeout(() => {
this.setState(getNextState());
}, 5000);
and
getNextState() {
if (this.state.postType === 'star_rating')
return { postType: 'image_poll' };
if (this.state.postType === 'image_poll')
return { postType: 'third_state' };
return { postType: 'star_rating' };
}
Upvotes: 1