Add useNavigatorOnLine hook

This commit is contained in:
Angelos Chalaris
2019-09-11 09:17:26 +03:00
committed by GitHub
parent 09334a33b3
commit b8e2e466d7

View File

@ -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 <span>You are {isOnline ? "online" : "offline"}.</span>;
};
ReactDOM.render(<StatusIndicator />, document.getElementById("root"));
```