码迷,mamicode.com
首页 > 其他好文 > 详细

[React] Detect user activity with a custom useIdle React Hook

时间:2019-02-07 17:47:19      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:you   http   idt   ssi   false   htm   temp   hello   overflow   

If the user hasn‘t used your application for a few minutes, you may want to log them out of the application automatically in case they‘ve stepped away from the machine and someone nefarious attempts to use their session. Let‘s checkout how you can create a custom React hook that wraps a regular npm module called activity-detector to solve this problem.

 

import React from "react";
import ReactDOM from "react-dom";
import createActivityDetector from "activity-detector";

import "./styles.css";

function useIdle(options) {
  const [isIdle, setIsIdle] = React.useState(false);
  React.useEffect(() => {
    const activityDetector = createActivityDetector(options);
    activityDetector.on("idle", () => setIsIdle(true));
    activityDetector.on("active", () => setIsIdle(false));

    // clean the subscription
    return () => {
      activityDetector.stop();
    };
  });
  return isIdle;
}

function App() {
  const isIdle = useIdle({ timeToIdle: 1000 });
  return (
    <div className="App">
      {!isIdle ? <div>Hello World</div> : <div>Are you there?</div>}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

 

UseEffect

 

 

[React] Detect user activity with a custom useIdle React Hook

标签:you   http   idt   ssi   false   htm   temp   hello   overflow   

原文地址:https://www.cnblogs.com/Answer1215/p/10354958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!