Skip to content

Commit 4fe7e00

Browse files
committed
feat(shared/hooks): useOnline
1 parent c113142 commit 4fe7e00

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

packages/shared/src/hooks/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ export * from './useValueWithPrev';
1919
export * from './useUniqueRoot';
2020
export * from './useStateRef';
2121
export * from './useFollowingState';
22+
export * from './useOnlineStatus';
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { useSyncExternalStore } from 'react';
2+
3+
/**
4+
* 监听网络状态,可能没什么用,主要是看看 useSyncExternalStore 是怎么用的
5+
*
6+
*/
7+
export function useOnlineStatus(): boolean {
8+
return useSyncExternalStore(subscribe, () => navigator.onLine);
9+
}
10+
const subscribe: Parameters<typeof useSyncExternalStore>[0] = (callback) => {
11+
window.addEventListener('online', callback);
12+
window.addEventListener('offline', callback);
13+
return () => {
14+
window.removeEventListener('online', callback);
15+
window.removeEventListener('offline', callback);
16+
};
17+
};
18+
19+
/**
20+
* useOnlineStatus 约等于以下代码
21+
*/
22+
// function useOnlineStatusImpl(): boolean {
23+
// const [online, setOnline] = useState(() => navigator.onLine);
24+
// useEffect(() => {
25+
// const callback = (): void => setOnline(navigator.onLine);
26+
// window.addEventListener('online', callback);
27+
// window.addEventListener('offline', callback);
28+
// return (): void => {
29+
// window.removeEventListener('online', callback);
30+
// window.removeEventListener('offline', callback);
31+
// };
32+
// }, []);
33+
// return online;
34+
// }

0 commit comments

Comments
 (0)