use-signalr
Reference

API reference

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

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

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

export const signalR = createSignalRClient({ hubs });

export const {
  useSignalR,
  useHubConsumer,
  useHubStatus,
  useSignalREvent,
  useSignalRInvoke,
  useSignalRSend,
  useSignalRTeardown,
  useOnReconnected,
} = signalR;

The function has this signature:

function createSignalRClient<const H extends Record<HubString, HubDef>>(
  config: SignalRClientConfig<H>,
): Plugin<[SignalROptions]> & { useSignalR, useHubConsumer, useHubStatus, ... }

The result has two roles. It is a Vue plugin: install it with app.use(signalR, options), as Plugin describes. It also carries the composables as properties. Types come from the contract that config.hubs declares. For the options of config, see Configuration reference.

Members

Every composable binds to the active effect scope. A component's setup() has one. Outside a component, run the call in an effectScope(). The library reads the hub, event, and method arguments one time, when you call the composable.

All composables except useSignalR 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
useSignalRuseSignalR()SignalRPublicContextReads the context. No scope needed.no
useHubConsumeruseHubConsumer(hub)voidScope disposalyes
useHubStatususeHubStatus(hub)Readonly<Ref<HubConnectionStatus>>. Each hub has its own ref.Scope disposalyes
useSignalREventuseSignalREvent(hub, event, handler)voidScope disposal removes the handler.yes
useSignalRInvokeuseSignalRInvoke(hub, method, options?)(...args) => Promise<Return>Scope disposal aborts waiting calls, unless keepAliveOnUnmount is true.yes
useSignalRSenduseSignalRSend(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.Scope disposalyes
useSignalRTeardownuseSignalRTeardown(hub, method, options?)(...args) => Promise<boolean>: true when the call is sent, false otherwise. It never rejects.Survives scope disposal.yes, and each call holds the hub until it ends
useOnReconnecteduseOnReconnected(hub, callback)voidScope disposal 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

useSignalR

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

useSignalRInvoke waits for the connection, calls the method, and resolves with the typed result. useSignalRTeardown is for a cleanup, for example in onUnmounted. It waits for the hub to connect and then sends. useSignalREvent and useOnReconnected pass an error that a handler throws to onError with info.source set to "callback". The subscription of useSignalREvent survives reconnects and rebuilds. useOnReconnected does not run after the first connection.

Templates unwrap the ref of useHubStatus. In a script, read .value.

For the options of useSignalRInvoke and useSignalRTeardown, see Configuration reference. For the rules of each call, see Calls.

Types

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

TypeMeaning
MaybeRefOrGetterA plain value, a ref, a computed ref, or a getter. This is the Vue type.
SignalROptionsThe options of app.use(signalR, options).
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.
HubStatusRefThe read-only ref that useHubStatus returns. Its value is a HubConnectionStatus.
HubConnectionStatus"idle", "connecting", "connected", "reconnecting", or "disconnected".
SignalRErrorInfoThe third argument of onError. source is "connection" or "callback".
SignalRPublicContextThe result of useSignalR().
InvokeOptionsThe options of useSignalRInvoke.
TeardownOptionsThe options of useSignalRTeardown.
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