Last active
April 2, 2019 16:31
-
-
Save reecelucas/52449286f0bca95241c0c88814e8a307 to your computer and use it in GitHub Desktop.
Simple network connectivity hook
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 { useState, useEffect } from 'react'; | |
/** | |
* navigator.onLine behaves a little differently across browsers | |
* (https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine#Specification). | |
* For bullet-proof detection you can add to this hook using some of the suggestions | |
* mentioned here https://www.html5rocks.com/en/mobile/workingoffthegrid/. | |
* | |
* Usage: | |
* const isOnline = useNetworkConnectivity(); | |
*/ | |
export default () => { | |
const [isOnline, setIsOnline] = useState(null); | |
useEffect(() => { | |
setIsOnline( | |
typeof navigator.onLine === 'boolean' ? navigator.onLine : true | |
); | |
window.addEventListener('online', goOnline); | |
window.addEventListener('offline', goOffline); | |
return () => { | |
window.removeEventListener('online', goOnline); | |
window.removeEventListener('offline', goOffline); | |
}; | |
}, []); | |
const goOnline = () => { | |
setIsOnline(true); | |
}; | |
const goOffline = () => { | |
setIsOnline(false); | |
}; | |
return isOnline; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment