Files
30-seconds-of-code/snippets/useNavigatorOnLine.md
Angelos Chalaris f39deb9522 Update to React 18
2023-04-14 20:32:31 +03:00

1.5 KiB

title, tags, author, cover, firstSeen, lastUpdated
title tags author cover firstSeen lastUpdated
React useNavigatorOnLine hook hooks,state,effect chalarangelo digital-nomad-7 2019-09-11T09:17:26+03:00 2020-11-16T14:17:53+02:00

Checks if the client is online or offline.

  • Create a function, getOnLineStatus, that uses the Navigator.onLine web API to get the online status of the client.
  • Use the useState() hook to create an appropriate state variable, status, and setter.
  • Use the useEffect() hook to add listeners for appropriate events, updating state, and cleanup those listeners when unmounting.
  • Finally return the status state variable.
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;
};
const StatusIndicator = () => {
  const isOnline = useNavigatorOnLine();

  return <span>You are {isOnline ? 'online' : 'offline'}.</span>;
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <StatusIndicator />
);