UNPKG

seitu

Version:
49 lines (48 loc) • 1.39 kB
import { createReadableSubscription, createSubscription } from "../../core/subscription/index.mjs"; //#region src/web/is-online/index.ts /** * Reactive browser online status. On the server, `get()` and the SSR snapshot * are `true`. * * @example Vanilla * ```ts twoslash * import { createIsOnline } from 'seitu/web' * * const isOnline = createIsOnline() * * isOnline.subscribe(value => { * console.log(value ? 'online' : 'offline') * }) * * console.log(isOnline.get()) * ``` * * @example React * ```tsx twoslash title="page.tsx" * import { createIsOnline } from 'seitu/web' * import { useSubscription } from 'seitu/react' * * const isOnline = createIsOnline() * * function Status() { * const online = useSubscription(isOnline) * return online ? 'Connected' : 'Disconnected' * } * ``` */ function createIsOnline() { const { subscribe, notify } = createSubscription({ onFirstSubscribe: () => { if (typeof window === "undefined") return; const handler = () => notify(); window.addEventListener("online", handler); window.addEventListener("offline", handler); return () => { window.removeEventListener("online", handler); window.removeEventListener("offline", handler); }; } }); const get = () => typeof navigator === "undefined" ? true : navigator.onLine; return createReadableSubscription(get, subscribe, notify, () => true); } //#endregion export { createIsOnline };