How to auto log off when a user is inactive in ReactJS?
If you are using the react-router
library to add front-end route configuration, you can fire a function whenever a user navigates to another page.
<Route path="/" onEnter={onUserNavigate} onChange={onUserNavigate}>
...
</Route>
Then you can have your event handler function calculate the time between to user navigations.
N.B. This is only a skeleton code (serves as a prototype for your actual method)
function onUserNavigate() {
let idleTime = getCurrentTime() - getPreviousNavTime();
storeCurrentNavTime();
if (idleTime > ALLOWED_IDLE_TIME)
window.location.href = '#/security/logout';
}
So, the above function assumes that,
- You have a method to get the current time (
getCurrentTime
function) - You have a method to store and get timestamps when a user navigates to a page
- You have a constant called
ALLOWED_IDLE_TIME
to store the minimum allowed idle time the user spends between two pages. - You have a logout URL (valued
#/security/logout
in the example code above) - The user isn't expected to interact with the page without navigating through the react-router paths. For example, the user may interact with the page using a browser console beyond the allowed idle time.
For timestamp related calculations and methods you can use any JavaScript library like momentjs
Hope that helped.
UPDATE There is an unnecessary binding around the part }.bind(this), 1000);
Just remove the .bind(this)
segment.
Plus, the startTimer() {
fragment should give you syntax error. For that you should remove the startTimer() {
line and its corresponding closing }
line
Accepted answer may do the job for you , but the time between navigating routes is not the real "in-active" time.
react-idle can do this , read the documentations and you can do it the way it should be.