Reputation: 386
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')
);
Upvotes: 16
Views: 36399
Reputation: 2784
Simplest approach is to use the react-idle-timer
package. Use the code below at the App.js
level:
import { useIdleTimer } from 'react-idle-timer';
export default function App() {
const onIdle = () => {
console.log('fires after 10 minutes');
//insert any custom logout logic here
}
const { getRemainingTime } = useIdleTimer({
onIdle,
timeout: 10 * 60 * 1000, //10 minute idle timeout
})
return (
//your App code
);
}
Docs: https://idletimer.dev/docs/features/idle-detection
NPM: https://npmjs.com/package/react-idle-timer
Upvotes: 2
Reputation: 302
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.
Upvotes: 19
Reputation: 3418
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
Upvotes: 7