Swr: Check user internet connection

Created on 3 Jun 2020  路  3Comments  路  Source: vercel/swr

I am using swr example with axios that use, useRequest hook. How can I show an alert when user not connected to internet!? When is offline

Most helpful comment

鈽濓笍 you can do it without involving SWR at all, as an example you could create your own hook to do it:

function useOnlineStatus() {
  const [status, setStatus] = React.useState<"online" | "offline">("online");

  React.useEffect(() => {
    function online() {
      setStatus("online");
    }

    function offline() {
      setStatus("offline");
    }

    window.addEventListener("online", online);
    window.addEventListener("offline", offline);

    return () => {
      window.removeEventListener("online", online);
      window.removeEventListener("offline", offline);
    };
  }, [setStatus]);

  return status;
}

And you can use it as:

const onlineStatus = useOnlineStatus()
if (onlineStatus === "offline") return (<OfflineBanner />)

All 3 comments

@zahraHaghi browser support online/offline event, you can display the alert based on the "offline" event. https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/Online_and_offline_events

鈽濓笍 you can do it without involving SWR at all, as an example you could create your own hook to do it:

function useOnlineStatus() {
  const [status, setStatus] = React.useState<"online" | "offline">("online");

  React.useEffect(() => {
    function online() {
      setStatus("online");
    }

    function offline() {
      setStatus("offline");
    }

    window.addEventListener("online", online);
    window.addEventListener("offline", offline);

    return () => {
      window.removeEventListener("online", online);
      window.removeEventListener("offline", offline);
    };
  }, [setStatus]);

  return status;
}

And you can use it as:

const onlineStatus = useOnlineStatus()
if (onlineStatus === "offline") return (<OfflineBanner />)

Thank you @sergiodxa @huozhi for helping!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bcomnes picture bcomnes  路  3Comments

Ephys picture Ephys  路  3Comments

nainardev picture nainardev  路  4Comments

tiagocorreiaalmeida picture tiagocorreiaalmeida  路  3Comments

bywo picture bywo  路  4Comments