Skip to content

Commit 3dc6e9c

Browse files
committed
add network information context, provider, and hook
1 parent bb9bf86 commit 3dc6e9c

3 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { useContext } from "react";
2+
import { NetworkInformationContext } from "../providers/network-information/network-information-context";
3+
4+
export default function useNetworkInformation() {
5+
const state = useContext(NetworkInformationContext);
6+
7+
return state;
8+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import React from "react";
2+
3+
export interface NetworkInformation {
4+
isOnline: boolean;
5+
}
6+
7+
export const NetworkInformationContext = React.createContext<
8+
NetworkInformation
9+
>({
10+
isOnline: true,
11+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { useCallback, useEffect, useState } from "react";
2+
import {
3+
NetworkInformation,
4+
NetworkInformationContext,
5+
} from "./network-information-context";
6+
7+
const NetworkInformationProvider: React.FC = ({ children }) => {
8+
const [state, setState] = useState<NetworkInformation>();
9+
10+
const loadNetworkInformation = useCallback(() => {
11+
const { onLine: isOnline } = window.navigator;
12+
13+
setState((prev) => ({
14+
...prev,
15+
isOnline,
16+
}));
17+
}, []);
18+
19+
useEffect(() => {
20+
const { connection } = window.navigator as any;
21+
22+
connection?.addEventListener("change", loadNetworkInformation);
23+
24+
loadNetworkInformation();
25+
26+
return () => {
27+
connection?.removeEventListener("change", loadNetworkInformation);
28+
};
29+
}, [loadNetworkInformation]);
30+
31+
return (
32+
<NetworkInformationContext.Provider value={state}>
33+
{children}
34+
</NetworkInformationContext.Provider>
35+
);
36+
};
37+
38+
export default NetworkInformationProvider;

0 commit comments

Comments
 (0)