forked from EFUB/efub4-react-hooks-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path#2.5.useNetwork.js
36 lines (33 loc) · 1016 Bytes
/
#2.5.useNetwork.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
const useNetwork = (onChange) => {
const [status, setStatus] = useState(navigator.onLine);
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 handleNetworkChange = (online) => {
console.log(online ? "We just went online" : "We are offline");
};
const onLine = useNetwork(handleNetworkChange);
return (
<div className="App">
<h1>{onLine ? "Online" : "Offline"}</h1>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);