Session timeout warning modal using react

abhi picture abhi · Aug 4, 2016 · Viewed 20.6k times · Source

I have a requirement to display timeout warning modal after 13 mins of inactivity and end session after 15 mins if user takes no action. I need to achieve this using reactjs. I checked react-timeout at https://www.npmjs.com/package/react-timeout#react-classic-verbose, but that didn't help. If anyone knows of a way to do this, please share with me.

Answer

Anshul Jain picture Anshul Jain · Nov 13, 2017

You can create a higher order component like this and can pass child component through higher order component

HOC:

`// code

export default function(ComposedClass) {
  class AutoLogout extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        warningTime: 1000 * 60 * 10,
        signoutTime: 1000 * 60 * 15,
      };
    }

    componentDidMount() {
      this.events = [
        'load',
        'mousemove',
        'mousedown',
        'click',
        'scroll',
        'keypress'
      ];

      for (var i in this.events) {
        window.addEventListener(this.events[i], this.resetTimeout);
      }

      this.setTimeout();
    }

    clearTimeoutFunc = () => {
      if (this.warnTimeout) clearTimeout(this.warnTimeout);

      if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
    };

    setTimeout = () => {
      this.warnTimeout = setTimeout(this.warn, this.state.warningTime);
      this.logoutTimeout = setTimeout(this.logout, this.state.signoutTime);
    };

    resetTimeout = () => {
      this.clearTimeoutFunc();
      this.setTimeout();
    };

    warn = () => {
      window.alert("You will be logged out automatically in 1 minute")
      console.log('You will be logged out automatically in 1 minute.');
    };

    logout = () => {
      // Send a logout request to the API
      console.log('Sending a logout request to the API...');
      this.destroy();
    };

    destroy = () => {
     //clear the session
      browserHistory.push('/');
      window.location.assign('/');
    };

    render() {

      return (
        <div>
          <ComposedClass {...this.props} />
        </div>
      );
    }
  }
}

`

You can wrap this HOC to all those component in which you want to give user warning due to inactivity, in routing file

<Route path="/test" component={HOC(comonent)} />

in above code component will be the page where you want to add this functionality.