Navigating to other component after user remains idle for 10 seconds

370 views Asked by At

I want to navigate to /oauth2/token when the user remains idle for 10 seconds,but in my code after 10 seconds its not navigating to /oauth2/token

below is my code:

export default function Timeout(){
const idleTimerRef = useRef(null);
const [isUserIdle, setIsUserIdle] = useState(false);

const userIdle = (state) => {
setIsUserIdle(state);
};
return (
<div className="App">
<IdleTimer
  ref={idleTimerRef}
  timeout={10000}
  onIdle={() => userIdle(true)}
  onActive={() => userIdle(false)}
></IdleTimer>
{isUserIdle ? <Redirect to='/oauth2/token'/> : <Home />}
)}
1

There are 1 answers

0
Blind2k On

I would use the hooks: useEffect and useHistory from router-dom.

const history = useHistory();
const MINUTE_MS = 100000; //NOT SURE ABOUT THE CORRCET NUMBER SHOULD BE HERE

useEffect(() => {
  const interval = setInterval(() => {
    history.push("/oauth2/token")
  }, MINUTE_MS);

  return () => clearInterval(interval); // This represents the unmount function, in which you need to clear your interval to prevent memory leaks.
}, [])

Dont forget to import useHistory and useEffect