Last active
May 20, 2019 08:15
-
-
Save andeersg/1decf8b76fae6bb1af63467f32a14ef3 to your computer and use it in GitHub Desktop.
A simple React hook to get online status and listen for changes
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, { useState } from 'react'; | |
import useOnlineStatus from './useOnlineStatus'; | |
const Example = () => { | |
const [onlineStatus, setOnlineStatus] = useState(navigator.onLine); | |
useOnlineStatus((isOnline) => { | |
setOnlineStatus(isOnline); | |
}); | |
return ( | |
<h3>This site is {onlineStatus ? 'online' : 'offline'}</h3> | |
); | |
}; | |
export default Example; |
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, { useEffect, useRef } from 'react'; | |
function useOnelineStatus(callback) { | |
const savedCallback = useRef(); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
const isOnline = () => { | |
savedCallback.current(true); | |
}; | |
const isOffline = () => { | |
savedCallback.current(false); | |
}; | |
useEffect(() => { | |
savedCallback.current(navigator.onLine); | |
window.addEventListener('online', isOnline); | |
window.addEventListener('offline', isOffline); | |
return () => { | |
window.removeEventListener('online', isOnline); | |
window.removeEventListener('offline', isOffline); | |
} | |
}, []); | |
} | |
export default useOnelineStatus; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment