I need to know if there is any API in REACT JS or HTML5 which provides the functionality of auto-log off when a user is inactive. My code is below I don't know what is wrong it is giving me the error startTimer is not defined and unnecessary binding. Please tell me where I am going wrong
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
class Toogle extends React.Component {
constructor(props) {
super(props);
//step 1
this.handleClick = this.handleClick.bind(this);
this.startTimer=this.startTimer.bind(this)
}
handleClick() {
console.log('Button is clicked');
// clearTimeout(timeoutTimer);
startTimer() {
var timeoutTimer = setTimeout(function() {
window.location.href = '#/security/logout';
}.bind(this), 1000);
}
}
render() {
return (
<div onMouseMove={this.handleClick}>
Move the cursor over me
</div>
);
}
}
ReactDOM.render(
<Toogle />,
document.getElementById('root')
);
Create a function that logs out user after 10 secs using setTimeout . Each time any of the event is triggered, i.e mousemove , click , scroll , keypress etc, the timer to logout user after 10 secs of inactivity resets.
How to use setTimeout in React. The setTimeout function accepts two arguments: the first is the callback function that we want to execute, and the second specifies the timeout in milliseconds before the function will be called. setTimeout(() => console. log('Initial timeout!'
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.
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,
getCurrentTime
function)ALLOWED_IDLE_TIME
to store the minimum allowed idle time the user spends between two pages.#/security/logout
in the example code above)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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With