Last active
May 20, 2020 11:01
-
-
Save DRFR0ST/b913c4a7c015e041d91482ac43d0b231 to your computer and use it in GitHub Desktop.
🎣 React Native hook for checking internet connection.
This file contains 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 { useRef, useState } from 'react'; | |
import NetInfo from "@react-native-community/netinfo"; | |
/** | |
* Returns information about internet connectivity. | |
* @example const [isConnected, checkConnection] = useConnectivity(); | |
*/ | |
export const useConnectivity = () => { | |
const [ isConnected, setConnected ] = useState<boolean | null>(null); | |
const ref = useRef<[ typeof isConnected, () => void ] | null>(null); | |
if(ref.current === null) { | |
const checkConnection = () => { | |
NetInfo.fetch().then(state => { | |
setConnected(!!state.isConnected); | |
}); | |
} | |
ref.current = [isConnected, checkConnection]; | |
ref.current[1](); | |
} | |
ref.current[0] = isConnected; | |
return ref.current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment