Overview
ws(url, config?) creates a typed WebSocket connection with a reactive status atom, send, connect, and disconnect.
Subscribe to messages with onSocket(handler, [socket]) inside a component — handlers are removed automatically on unmount. Prefer the dedicated onSocket hook page for the subscribe-only API.
ws vs onSocket
|
API
|
Role
|
Notes
|
|---|---|---|
ws(url, config?)
| Connection | Returns WsConnection — send, status, connect/disconnect. |
onSocket(fn, sockets)
| Subscribe | Component-scoped message handler; auto-cleanup. |
WsConfig quick reference
import { ws } from 'mates';
import type { WsConfig } from 'mates';
const config: WsConfig = {
reconnect: true, // default true
reconnectDelay: 1000, // ms before first retry
reconnectMaxDelay: 30_000, // backoff cap
reconnectMaxAttempts: Infinity,
protocols: ['json'],
auth: () => ({ token: '…' }), // lazy query params each connect
autoConnect: true, // false → call connect() yourself
};
// Inside a component outer function only:
const socket = ws('wss://api.example.com/ws', config);
socket.send({ type: 'ping' });
socket.status(); // reactive atom
socket.disconnect();
Simulated message stream (offline)
Docs sandbox has no WebSocket server. This mirrors onSocket + status with onInterval.
Status atom pattern
chat.status() cycles connecting → connected → disconnected → error in a real connection.