From b8e2e466d799c1e266d5341d40bffa984f77ce38 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Wed, 11 Sep 2019 09:17:26 +0300 Subject: [PATCH] Add useNavigatorOnLine hook --- snippets/useNavigatorOnLine.md | 47 ++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 snippets/useNavigatorOnLine.md diff --git a/snippets/useNavigatorOnLine.md b/snippets/useNavigatorOnLine.md new file mode 100644 index 000000000..52fabdaf1 --- /dev/null +++ b/snippets/useNavigatorOnLine.md @@ -0,0 +1,47 @@ +--- +title: useNavigatorOnLine +tags: hooks,state,effect,intermediate +--- + +A hook that returns if the client is online or offline. + +- Create a function, `getOnLineStatus`, that uses the `NavigatorOnLine` web API to get the online status of the client. +- Use the `React.useState()` hook to create an appropriate state variable, `status`, and setter. +- Use the `React.useEffect()` hook to add listeners for appropriate events, updating state, and cleanup those listeners when unmounting. +- Finally return the `status` state variable. + +```jsx +const getOnLineStatus = () => + typeof navigator !== "undefined" && typeof navigator.onLine === "boolean" + ? navigator.onLine + : true; + +const useNavigatorOnLine = () => { + const [status, setStatus] = React.useState(getOnLineStatus()); + + const setOnline = () => setStatus(true); + const setOffline = () => setStatus(false); + + React.useEffect(() => { + window.addEventListener("online", setOnline); + window.addEventListener("offline", setOffline); + + return () => { + window.removeEventListener("online", setOnline); + window.removeEventListener("offline", setOffline); + }; + }, []); + + return status; +}; +``` + +```jsx +const StatusIndicator = () => { + const isOnline = useNavigatorOnLine(); + + return You are {isOnline ? "online" : "offline"}.; +}; + +ReactDOM.render(, document.getElementById("root")); +```