DEV Community

kumar_lav
kumar_lav

Posted on

Implementing AutoLogout Feature in Class Components(React-JS)

We have noticed that financial applications, log automatically after a certain time of inactivity. This feature is particularly important when dealing with sensitive web applications like financial apps.

NOTE:

In MainDashboardEntry (this should be the base entry file for all component routes),

talking about the solution

When the component mounts, add listeners to the window that listens to the events.
Create a function that logs out a user after 10 seconds using set Timeout.
Each time any of the events is triggered, i.e. mouse move, click, scroll, keypress, etc., the timer to log out the user after 10 seconds of inactivity resets.
However, if none of the events is triggered within 10 seconds, that is app is inactive, the app automatically logs out.

mentioning are some points below these user events to guarantee user activity on the application

let timer;
const events = [
"load",
"mousemove",
"mousedown",
"Click",
"scroll",
"keypress",
];

Note: these variables should be

`class IdleTimerContainer extends React.Component {
constructor(props: any) {
super(props);
}
handleLogoutTimer() {
timer = setTimeout(() => {
// clears any pending timer.
this.resetTimer();
// Listener clean up. Removes the existing event listener from the window
Object.values(events).forEach((item) => {
window.removeEventListener(item, this.resetTimer);
console.log("2 second")
});
// logs out user
this.logoutAction();
}, 2000); // 10000ms = 10secs. You can change the time.
};
resetTimer (){
if (timer) clearTimeout(timer);
};
componentDidMount(): void {
Object.values(events).forEach((item) => {
window.addEventListener(item, () => {
this.resetTimer();
this.handleLogoutTimer();
});
});
}
logoutAction = () => {
localStorage.clear();
window.location.pathname = "/"; // login page while the user is an inactive redirect to login page we can set the path accordingly
};

export default IdleTimerContainer;

//If you are using this functionality we can use the useEffect

`

Top comments (0)