-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathuseNavigatorOnline.ts
More file actions
33 lines (26 loc) · 994 Bytes
/
Copy pathuseNavigatorOnline.ts
File metadata and controls
33 lines (26 loc) · 994 Bytes
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
import { useEffect, useState } from 'react';
/**
* Retrieves the current online status of the browser.
* @returns {boolean} The online status of the browser.
*/
const getOnlineStatus = () =>
typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean' ? navigator.onLine : true;
/**
* A custom React hook that tracks the online status of the browser.
* @returns {boolean} The current online status of the browser.
*/
const useNavigatorOnline = () => {
const [status, setStatus] = useState(getOnlineStatus());
const setOnline = () => setStatus(true);
const setOffline = () => setStatus(false);
useEffect(() => {
window.addEventListener('online', setOnline);
window.addEventListener('offline', setOffline);
return () => {
window.removeEventListener('online', setOnline);
window.removeEventListener('offline', setOffline);
};
}, []);
return status;
};
export default useNavigatorOnline;