[강의노트] [React] useNetwork

Sejeong Yang·2021년 3월 15일
0

React

목록 보기
8/12
post-custom-banner
const useNetwork = onChange => {
  const [status, setStatus] = useState(navigator.onLine); // true 또는 false 값
  const handleChange = () => {
    if (typeof onChange === "function") {
      onChange(navigator.onLine);
    }
    setStatus(navigator.onLine);
  };
  useEffect(() => {
    window.addEventListener("online", handleChange);
    window.addEventListener("offline", handleChange);
    () => {
      window.removeEventListener("online", handleChange);
      window.removeEventListener("offline", handleChange);
    };
  }, []);
  return status;
};

const App = () => {
  const onNetworkChange = isOnline => { 
    console.log(isOnline ? "We are back online" : "We just got offline");
  };
  const online = useNetwork(onNetworkChange);
  return (
    <div className="App">
      <h1>{isOnline ? "We are online" : "We are offline"} </h1>
      <p>Welcome</p>
    </div>
  );
};
profile
Front End Developer
post-custom-banner

0개의 댓글