Browse guides

Respond to connectivity changes

Keep the interface current while the browser moves between network conditions.

The example reads the initial state, listens for changes, refreshes the status and removes its listeners during cleanup.

Table of contents

Main APIs

NetworkManager
Observes browser connectivity and signal quality.
NetworkEvent
Enumerates the ONLINE, OFFLINE and CHANGE network events.
SignalLevel
Identifies the connection signal returned by NetworkManager from None through Excellent.
NetworkError
Represents a public network failure that the application can handle.
NetworkManagerRuntime
Type. Environment objects used by NetworkManager.
ts
import { mount, onCreate, update } from "valyrian.js";
import { NetworkEvent, NetworkManager, SignalLevel } from "valyrian.js/network";

const network = new NetworkManager();
let online = network.getStatus().online;
let signal = network.getSignalLevel();

const NetworkStatus = () => {
  onCreate(() => {
    const refreshStatus = (status: ReturnType<typeof network.getStatus>) => {
      online = status.online;
      signal = network.getSignalLevel();
      update();
    };
    const stopOnline = network.on(NetworkEvent.ONLINE, refreshStatus);
    const stopOffline = network.on(NetworkEvent.OFFLINE, refreshStatus);
    const stopChange = network.on(NetworkEvent.CHANGE, refreshStatus);

    return () => {
      stopOnline();
      stopOffline();
      stopChange();
      network.destroy();
    };
  });
  return `${online ? "Online" : "Offline"}; signal: ${SignalLevel[signal]}`;
};

mount("body", NetworkStatus);

Limit

Keep request errors and network status as related but distinct states.

Exact references