Browse recipes

React to connectivity changes

Keep one status current while the browser moves between network conditions.

Table of contents

APIs used

mount
Starts a Valyrian.js application on a DOM target.
onCreate
Runs when a component first enters the rendered tree and may return cleanup or a promise.
update
Requests a render pass for the mounted view.
NetworkEvent
Enumerates the ONLINE, OFFLINE and CHANGE network events.
NetworkManager
Observes browser connectivity and signal quality.
SignalLevel
Identifies the connection signal returned by NetworkManager from None through Excellent.

Run this recipe

Starting project
Use the local TSX and ESM project from Stage 1 with Valyrian.js installed and its ESM browser build configured.
File
Replace src/client-entry.tsx with this recipe snippet.
Run
Run npm run build, serve public with npx --yes serve@14.2.5 public --listen 8000, open http://localhost:8000 and use the example's visible controls.
Observable result
The view renders Online or Offline together with the current SignalLevel name.

Starting point

Read the initial connectivity state and SignalLevel, then observe subsequent network changes.

Steps

Subscribe when the view is created, update the online state and signal level on each change and destroy the manager during cleanup.

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);

Result

The view renders Online or Offline together with the current SignalLevel name.

Limits

Connectivity does not guarantee that a remote operation will succeed.

Continue