NetworkStatus

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.

Network Status is currently not available.

Usage

You can use NetworkStatus in alongside Previous to get both current and previous network status.

	<script lang="ts">
  import { NetworkStatus } from "runed";
  // checkout svelte-sonner for toasts (https://github.com/wobsoriano/svelte-sonner)
  import { toast } from "svelte-sonner";
 
  const networkStatus = new NetworkStatus();
  const previousNetworkStatus = new Previous(() => ({
    online: networkStatus.online,
    updatedAt: networkStatus.updatedAt
  }));
 
  $effect(() => {
    if (!networkStatus.isSupported) return;
 
    if (networkStatus.online === false) {
      toast.error("No internet connection.");
    }
    if (networkStatus.effectiveType === "2g") {
      toast.warning("You are experiencing a slow connection.");
    }
    if (networkStatus.online === true && previousNetworkStatus.current?.online === false) {
      toast.success("You are back online!");
    }
  });
</script>
 
{#if networkStatus.isSupported}
  <p>online: {networkStatus.online}</p>
{:else}
  <p>Network Status is currently not available.</p>
{/if}	

isSupported

It's important to check if the API is supported on the current environment/device before using it.

	const networkStatus = new NetworkStatus();
 
if (networkStatus.isSupported) {
  // do something with the network status
}	

Getting the previous status

It's often useful to get the previous status of the network connection. You can use the Previous utility to track the previous state.

	const networkStatus = new NetworkStatus();
const previousNetworkStatus = new Previous(() => ({
  online: networkStatus.online,
  updatedAt: networkStatus.updatedAt
}));	

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