-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseNetworkStatus.ts
44 lines (36 loc) · 1.02 KB
/
useNetworkStatus.ts
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
37
38
39
40
41
42
43
44
import { useState, useEffect } from 'react';
import { isClient } from '../utils';
interface NetworkStatus {
isOnline: boolean;
offlineAt: Date | undefined;
}
function getInitialValue(): boolean {
if (isClient && typeof navigator !== 'undefined') {
return navigator.onLine;
}
return false;
}
export const useNetworkStatus = (): NetworkStatus => {
const [status, setStatus] = useState<boolean>(getInitialValue());
const [offlineAt, setOfflineAt] = useState<Date | undefined>(undefined);
useEffect(() => {
const handleOnline = () => {
setStatus(true);
setOfflineAt(undefined);
};
const handleOffline = () => {
setStatus(false);
setOfflineAt(new Date());
};
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return {
isOnline: status,
offlineAt,
};
};