Last active
November 19, 2020 09:54
-
-
Save ourmaninamsterdam/d92a795c4f52ddaa5bac39c06fa12615 to your computer and use it in GitHub Desktop.
useDeviceOnline wrapper hook for React Native's NetInfo
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 NetInfo, { NetInfoState, NetInfoSubscription } from '@react-native-community/netinfo'; | |
import { useState, useRef, useEffect } from 'react'; | |
const useDeviceOnlineStatus = () => { | |
const [online, setOnline] = useState(false); | |
const unsubscribeRef = useRef<NetInfoSubscription | undefined>(); | |
useEffect(() => { | |
unsubscribeRef.current = NetInfo.addEventListener((state: NetInfoState) => { | |
setOnline(state.isConnected); | |
}); | |
return () => { | |
unsubscribeRef?.current && unsubscribeRef.current(); | |
}; | |
}, []); | |
return { online }; | |
}; | |
export default useDeviceOnlineStatus; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment