Charan Cherry Charan Cherry - 2 months ago 10
React JSX Question

How to clear interval function of one component from another?

Parent Component

handleSubmitValidateInput: function(e){
e.preventDefault();
var data = {phone: this._phone.value, pwd: this._pwd.value}
$.ajax({
type: 'POST',
data:data,
url: 'http://localhost:3000/login',
success: function(data){
ReactDOM.render(<Home UserDetails={data}/>, document.getElementById('content'));
var idleTime = 0;
var interval = setInterval(function(){
// some code
});
}, (1000));
},
error: function(error){
console.log('Error login!!');
}
});
},


I want to clear the
interval
from the Home component. How can I achieve this? Please explain this to me. The function below is of the Home component.
I want to clear the interval from logout function.

handleLogout: function(e){
e.preventDefault();
console.log('Cleared');
localStorage.clear();
ReactDOM.render(<Login />, document.getElementById('content'));
},

Answer

Instead of using a local variable, try using the window object.

window.interval = setInterval(function(){
  // some code
});

Then you can clear it from your logout function

handleLogout: function(e){
  e.preventDefault();
  clearTimeout(window.timeout);
  console.log('Cleared');
  localStorage.clear();
  ReactDOM.render(<Login />, document.getElementById('content'));
},

There are of course other ways of implementing this, if you'd rather not use the window object. This should be the shortest/easiest way however.


A simple Demo can be found here or in the snippet below. Check the console for output.

var Start = React.createClass({
  start: function() {
    console.log("Timeout started")
    window.timeout = setTimeout(function(){
      console.log("Timeout ended")
    }, 2000);
  },
  render: function() {
    return <button onClick={this.start}>Set Timeout</button>;
  }
});

var Stop = React.createClass({
  stop: function() {
    clearTimeout(window.timeout);
    console.log("Timeout cleared");
  },
  render: function() {
    return <button onClick={this.stop}>Clear Timeout</button>;
  }
});

ReactDOM.render(
  <div>
  	<Start />
    <Stop />
  </div>,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Comments