useNetworkStatus

Watch for network status changes.

Demo

To see it in action, try disabling and then re-enabling your Internet connection. If you're using Google Chrome, you can also artificially throttle the network to test its behavior under different conditions.

Usage

You can use useNetworkStatus() to retrieve both current and previous network status. It must be used within the browser context, otherwise it will return null.

	<script lang="ts">
  import { useNetworkStatus } from "runed";
  import { toast } from "svelte-sonner";
 
  const networkStatus = useNetworkStatus();
 
  $effect(() => {
    if (!networkStatus.current) {
      return;
    }
    if (networkStatus.current.online === false) {
      toast.error("No internet connection.");
    }
    if (networkStatus.current.effectiveType === "2g") {
      toast.warning("You are experiencing a slow connection.");
    }
    if (networkStatus.current.online === true && networkStatus.previous?.online === false) {
      toast.success("You are back online!");
    }
  });
</script>
 
 
{#if networkStatus.current}
    <p>online: {networkStatus.current.online}</p>
{/if}	

Current

You can get the current status by calling the current method.

	const networkStatus = useNetworkStatus();
 
networkStatus.current;	

Previous

You can get the previous status by calling the previous method. It defaults to undefined if the network status hasn't been updated since the component mounted.

	const networkStatus = useNetworkStatus();
 
networkStatus.previous;	

Reference

The returned status always includes online and updatedAt. Other properties are returned based on the NetworkInformation interface and depend on your browser's compatibility.

	interface NetworkStatus {
  online: boolean;
  updatedAt: Date;
  downlink?: number;
  downlinkMax?: number;
  effectiveType?: "slow-2g" | "2g" | "3g" | "4g";
  rtt?: number;
  saveData?: boolean;
  type?: "bluetooth" | "cellular" | "ethernet" | "none" | "wifi" | "wimax" | "other" | "unknown";
}	
MIT

© 2024 Svecosystem Team