Reputation: 1471
I have react app with several routes rendering several components. How do i check user inactivity for all the pages. If user is inactive in any of the page for more than 5 mins, I want a function to be executed which does some operation, if user does some activities like click, enter etc the inactivity time should be reset back to 5 mins.
Looked into these answers but wasn't able to do it.
How to detect idle time in JavaScript elegantly?
How to auto log off when a user is inactive in ReactJS?
Can it be done using only vanilla Javascript without any packages?
Thanks in advance !
Upvotes: 7
Views: 18946
Reputation: 149
Package react-idle-timer will do the work for you.
You can install it like this,
sudo npm install react-idle-timer
or
npm install react-idle-timer --save
import React, { Component } from 'react'
import IdleTimer from 'react-idle-timer'
export default class YourApp extends Component {
constructor(props) {
super(props)
this.idleTimer = null
this.handleOnAction = this.handleOnAction.bind(this)
this.handleOnActive = this.handleOnActive.bind(this)
this.handleOnIdle = this.handleOnIdle.bind(this)
}
render() {
return (
<div>
<IdleTimer
ref={ref => { this.idleTimer = ref }}
timeout={1000 * 60 * 15}
onActive={this.handleOnActive}
onIdle={this.handleOnIdle}
onAction={this.handleOnAction}
debounce={250}
/>
{/** Your app/component here. */}
</div>
)
}
handleOnAction (event) {
console.log('user did something', event)
}
handleOnActive (event) {
console.log('user is active', event)
console.log('time remaining', this.idleTimer.getRemainingTime())
}
handleOnIdle (event) {
console.log('user is idle', event)
console.log('last active', this.idleTimer.getLastActiveTime())
}
}
import React from 'react'
import { useIdleTimer } from 'react-idle-timer'
import App from './App'
export default function (props) {
const handleOnIdle = event => {
console.log('user is idle', event)
console.log('last active', getLastActiveTime())
}
const handleOnActive = event => {
console.log('user is active', event)
console.log('time remaining', getRemainingTime())
}
const handleOnAction = event => {
console.log('user did something', event)
}
const { getRemainingTime, getLastActiveTime } = useIdleTimer({
timeout: 1000 * 60 * 15,
onIdle: handleOnIdle,
onActive: handleOnActive,
onAction: handleOnAction,
debounce: 500
})
return (
<div>
{/** Your app/component here. */}
</div>
)
}
They offer a lot of feature which you can read here on GitHub at react-idle-timer
Upvotes: 13