Usage

useWS

The all-in-one composable to manage reactive WebSocket connections from client-side.

The useWS will be the main composable to manage WebSocket connections client-side. It automatically manage the states of the subscribed topics and the connection itself.

Used in conjunction with defineWSHandler and runtime configuration, it will provide a seamless experience for real-time communication as simple as doing const { states, send } = useWS().

Arguments

It only accepts two arguments, both of them optional.

topics

An array of strings representing the topics to subscribe to. These should not include those defined in your runtime configuration.

const { states, send } = useWS(['session', 'info'])

options

An optional object to override the default options for the WebSocket connection.

route
string

Defines the default route for useWS to connect to the WebSocket server. - Default to runtime configuration

heartbeat
boolean | object

Enables or disables the heartbeat mechanism. If an object is provided, it is possible to define the interval and the message to send. - Default to false

autoReconnect
boolean | object

Enables or disables the auto-reconnect mechanism. If an object is provided, it is possible to define the interval and the maximum number of attempts. - Default to false

immediate
boolean

The connection will be established immediately. - Default to true

autoConnect
boolean

Automatically connect to the websocket when route changes. - Default to true

autoClose
boolean

Automatically close the websocket when the component is unmounted. - Default to true

protocols
string[]

An array of strings representing the sub-protocols to use. - Default to []

Returns

It returns a number of properties and methods to manage the WebSocket connection and the subscribed topics.

states

A reactive object containing the states of all the subscribed topics.

const { states, send } = useWS<{
  session: {
    users: number
  }
}>(['session'])

console.log(states.session.users)

send

A function to send messages to the WebSocket server. It can accept multiple arguments, based on use-case, but always returns a boolean indicating if the message was sent successfully.

  • send(payload: string | ArrayBuffer | Blob): boolean
  • send(type: 'subscribe' | 'unsubscribe', topic: string): boolean
  • send(type: 'publish', topic: string, payload: any): boolean

The last two methods will always be transformed to string before being sent to the server.

const { states, send } = useWS<{
  chat: {
    user?: string,
    text: string,
  }[]
}>(['chat'])

const file = new Blob(['Hello, World!'], { type: 'text/plain' })
send(file)

send('publish', 'chat', { text: 'Hello, World!' })
Sending a payload directly without specifying the type and topic will send them as is and will not be automatically handled server-side.By contrast, specifying the type and topic will be handled automatically by the server if defineWSHandler is used and the target is not an internal topic.

data

A ref containing any extra data received from the server and not handled by states automatically.

const { data } = useWS()

// server sends 'Hello, World!' directly without publishing to a topic

console.log(data.value) // 'Hello, World!'

status

A ref containing the current status of the WebSocket connection.

const { status } = useWS()

console.log(status.value) // 'OPEN' | 'CONNECTING' | 'CLOSED'

open/close

Methods to manually open and close the WebSocket connection.

Internals

The following properties and methods are considered internal and should not be used directly. I decided to expose them for debugging purposes or advanced use-cases.

  • ws: The WebSocket instance.
  • _data: It contains any raw data received from the server.
  • _send: It is used under the hood to send messages to the server.

Type Support

As you might have noticed in the examples above, useWS accepts a type parameter. This is to provide type support for the states object.