Last active
October 5, 2022 16:53
-
-
Save reberthkss/ab67042534c500e8d7fe7b97bb5f7c3c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {createContext, useCallback, useContext, useEffect, useMemo, useState} from "react"; | |
import NetInfo, {NetInfoState} from "@react-native-community/netinfo"; | |
import changeNavigationBarColor from "react-native-navigation-bar-color"; | |
interface NetworkState { | |
readonly networkState: NetInfoState | null | |
} | |
interface NetworkAction { | |
isConnected: () => Boolean | |
} | |
interface Props { | |
state: NetworkState, | |
actions: NetworkAction | |
} | |
const NetworkContext = createContext<Props | null>(null) | |
const useNetworkContext = (): Props => { | |
const [networkState, setNetworkState] = useState<NetInfoState | null>(null) | |
const handleNetState = useCallback((state: NetInfoState) => { | |
setNetworkState(state) | |
}, [setNetworkState]) | |
const isConnected = useCallback(() => { | |
return networkState?.isConnected || false | |
}, [networkState]) | |
useEffect(() => { | |
const unsubscribe = NetInfo.addEventListener(handleNetState) | |
changeNavigationBarColor("black", false, true); | |
return () => { | |
unsubscribe() | |
} | |
}, []) | |
return useMemo(() => ( | |
{ | |
state: { | |
networkState | |
}, | |
actions: { | |
isConnected | |
} | |
} | |
), | |
[ | |
isConnected, | |
networkState | |
]) | |
} | |
export const useSafeNetworkContext = () => { | |
const context = useContext(NetworkContext); | |
if (context == null) throw Error("The component isn't wrapped by NetworkContextProvider!"); | |
return context; | |
} | |
const NetworkContextProvider: React.FC<any> = ({children}) => { | |
const context = useNetworkContext() | |
return ( | |
<NetworkContext.Provider value={context}> | |
{children} | |
</NetworkContext.Provider> | |
) | |
} | |
export default NetworkContextProvider |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment