-
Notifications
You must be signed in to change notification settings - Fork 0
/
useNetwork.js
28 lines (27 loc) · 953 Bytes
/
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
export 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);
return () => {
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>
// );
// };