use-signalr
Reference

API reference

Every export of the Svelte package, with signatures, return values, lifetimes, and placement errors.

The package @dammers/use-signalr-svelte has three runtime exports: createSignalRClient, event, and method. Everything else is a type. Call createSignalRClient one time, in a client module, and import the functions from there. The sample shows such a module:

client.ts
import { createSignalRClient } from "@dammers/use-signalr-svelte";
import { hubs } from "./contract";

export const {
  provideSignalR,
  getSignalR,
  keepHubAlive,
  onHubEvent,
  hubInvoke,
  hubSend,
  hubTeardown,
  hubStatus,
  onReconnected,
} = createSignalRClient({ hubs });

The function has this signature:

function createSignalRClient<const H extends Record<HubString, HubDef>>(
  config: SignalRClientConfig<H>,
): { provideSignalR, getSignalR, keepHubAlive, onHubEvent, hubInvoke, hubSend, hubTeardown, hubStatus, onReconnected }

The result is one object of functions. Types come from the contract that config.hubs declares. For the options of config, see Configuration reference.

Members

Call every function while a component initializes, in the <script> block or in a function that the block calls. The functions use getContext and onDestroy, so they need a component that is below the one that called provideSignalR. The library reads the hub, event, and method arguments one time.

All functions except provideSignalR and getSignalR hold a hub. A held hub counts as a consumer. A lazy hub connects with its first consumer. It closes after its last consumer leaves and graceMs has passed.

NameSignatureReturnsLifetimeKeeps a lazy hub alive
provideSignalRprovideSignalR(options)voidLives as long as the component that calls it.no (it holds no hub)
getSignalRgetSignalR()SignalRPublicContextReads the context.no
keepHubAlivekeepHubAlive(hub)voidComponent destroyyes
hubStatushubStatus(hub)Readable<HubConnectionStatus>: a store with only subscribe. Each hub has its own store.Component destroyyes
onHubEventonHubEvent(hub, event, handler)voidComponent destroy removes the handler.yes
hubInvokehubInvoke(hub, method, options?)(...args) => Promise<Return>Component destroy aborts waiting calls, unless keepAliveOnUnmount is true.yes
hubSendhubSend(hub, method)(...args) => Promise<boolean>: true when the call is sent, false when the hub is not connected or the send fails. It never rejects.Component destroyyes
hubTeardownhubTeardown(hub, method, options?)(...args) => Promise<boolean>: true when the call is sent, false otherwise. It never rejects.Survives component destroy.yes, and each call holds the hub until it ends
onReconnectedonReconnected(hub, callback)voidComponent destroy removes the callback.yes
eventevent<Args>()A marker that declares a server event. Args is the tuple of handler arguments.None. It carries types only.no
methodmethod<Args, Return>()A marker that declares a server method. Return defaults to void.None. It carries types only.no

provideSignalR

Builds the session and sets the context. It starts the connections in onMount, so nothing connects on the server. On the server, it disables the session. See Provider for the options and for the start and stop rules.

getSignalR

Returns the context object, typed to your contract:

MemberSignatureDescription
getConnection(hub) => HubConnection | nullThe raw connection, or null when there is none. Use it as a last resort.
getStatus(hub) => HubConnectionStatusA point read. It does not subscribe to changes.
waitForConnection(hub, timeoutMs, signal?) => Promise<HubConnection>Resolves when the hub is connected. It rejects on timeout, on abort, when the session is disabled, and when the hub stopped after a final error.

Calls

hubInvoke waits for the connection, calls the method, and resolves with the typed result. hubTeardown is for onDestroy. It waits for the hub to connect and then sends. onHubEvent and onReconnected pass an error that a handler throws to onError with info.source set to "callback". The subscription of onHubEvent survives reconnects and rebuilds. onReconnected does not run after the first connection.

For the options of hubInvoke and hubTeardown, see Configuration reference. For the rules of each call, see Calls.

Types

The package re-exports these types. Core defines most of them.

TypeMeaning
MaybeReadableT | Readable<T>: a plain value or a Svelte store.
SignalRProviderPropsThe options of provideSignalR.
SignalRClientConfigThe argument of createSignalRClient.
PerHubConfigPer-hub settings: lazy, graceMs, reconnect, logLevel, httpOptions, hubProtocol, configureBuilder.
HubDefOne hub entry in config.hubs: PerHubConfig plus events and methods.
EventDefThe marker that event() returns.
MethodDefThe marker that method() returns.
HubStringA hub path. It starts with /.
HubContractThe events and methods of one hub, as functions.
SignalRContractThe map of hub paths to HubContract.
InferContractThe contract that the library derives from the hubs config.
EventNameThe event names of one hub.
EventArgsThe handler arguments of one event.
MethodNameThe method names of one hub.
MethodArgsThe call arguments of one method.
MethodReturnThe resolved result of one method.
HubConnectionStatus"idle", "connecting", "connected", "reconnecting", or "disconnected".
SignalRErrorInfoThe third argument of onError. source is "connection" or "callback".
SignalRPublicContextThe result of getSignalR().
InvokeOptionsThe options of hubInvoke.
TeardownOptionsThe options of hubTeardown.
ReconnectConfigtrue, false, an array of delays in ms, or a custom retry policy.
HttpOptionsThe SignalR HTTP options, without accessTokenFactory.
HubProtocolConfigA hub protocol, or a function that returns one.
ConfigureBuilderA function that changes the HubConnectionBuilder on each build.
BuilderContextThe second argument of ConfigureBuilder: the hub path and the base URL.

Errors

For the error names and messages, and for the placement errors, see Troubleshooting. An AbortError is a DOMException. All other errors of a call are an Error with a name such as SignalRTimeoutError.

On this page