Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

State change after a certain amount of time with React.js

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?

like image 576
user1072337 Avatar asked Jul 09 '15 04:07

user1072337


People also ask

How do you change state continuously after a certain amount of time in React?

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.

How do you refresh every 5 seconds in React?

setTimeout(function () { location. reload(1); }, 5000);

Can we change state in react JS?

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).

How do I change state value in react JS?

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.


1 Answers

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
   }
}
like image 178
baao Avatar answered Oct 14 '22 21:10

baao