I have a certain variable that is being toggled between false and true as a state (we can call it submitted). What I would like to do is have the state change back to false after it has been set to true, after a few seconds. How would I do this?
I have this function that is called when a button is clicked, and where the state changes:
saveAndContinue: function(e) {
e.preventDefault()
if(this.state.submitted==false) {
email = this.refs.email.getDOMNode().value
this.setState({email: email})
this.setState({submitted: !this.state.submitted});
}
}
I would like to add to this, where I have a timer set the variable submitted back to false. How do I do this?
Use the set interval method inside the function to change the state after a fixed amount of time. setInterval method takes two parameter callback and time. The callback function is called again and again after that given amount of time. Use the setState method to change the state of the component.
setTimeout(function () { location. reload(1); }, 5000);
Changing the state ObjectTo change a value in the state object, use the this. setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).
To update our state, we use this. setState() and pass in an object. This object will get merged with the current state. When the state has been updated, our component re-renders automatically.
You can set a timeout to reset the state after a given amount of time. Remember to bind(this)
to the timeout function so that this
refers to the right this
saveAndContinue: function(e) {
e.preventDefault()
if(this.state.submitted==false) {
email = this.refs.email.getDOMNode().value
this.setState({email: email})
this.setState({submitted: !this.state.submitted});
setTimeout(function(){
this.setState({submitted:false});
}.bind(this),5000); // wait 5 seconds, then reset to false
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With