-
-
Save jeffrafter/8bab08f3efaac5e8a9350cd9dc05b3cc to your computer and use it in GitHub Desktop.
A basic hook to indicate if the user is online or offline
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, useEffect, useContext } from "react" | |
const OnlineStatusContext = React.createContext(true) | |
type Props = { | |
children: React.ReactNode | |
} | |
export const OnlineStatusProvider: React.FC<Props> = ({ children }) => { | |
const [onlineStatus, setOnlineStatus] = useState<boolean>(typeof navigator !== "undefined" ? navigator.onLine : false) | |
const setOnline = () => setOnlineStatus(true) | |
const setOffline = () => setOnlineStatus(false) | |
useEffect(() => { | |
window.addEventListener("offline", setOffline) | |
window.addEventListener("online", setOnline) | |
return () => { | |
window.removeEventListener("offline", setOffline) | |
window.removeEventListener("online", setOnline) | |
} | |
}, []) | |
return <OnlineStatusContext.Provider value={onlineStatus}>{children}</OnlineStatusContext.Provider> | |
} | |
export const useOnlineStatus = () => { | |
const store = useContext(OnlineStatusContext) | |
return store | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment