useWebSocket
Hook that connects to a WebSocket server and handles incoming and outgoing messages
browser
test coverage
Last changed: last month
Installation
Library
CLI
Manual
typescript
import { useWebSocket } from '@siberiacancode/reactuse';
Usage
typescript
const { status, close, send, open, client } = useWebSocket('url');
Demo
Api
Parameters
Name | Type | Default | Note |
---|---|---|---|
url | UseWebSocketUrl | - | The URL of the WebSocket server |
options.onConnected? | (webSocket: WebSocket) => void | - | The callback function that is called when the WebSocket connection is established |
options.onDisconnected? | (event: CloseEvent, webSocket: WebSocket) => void | - | The callback function that is called when the WebSocket connection is closed |
options.onError? | (event: Event, webSocket: WebSocket) => void | - | The callback function that is called when an error occurs |
options.onMessage? | (event: MessageEvent, webSocket: WebSocket) => void | - | The callback function that is called when a message is received |
options.retry? | boolean | number | - | The number of times to retry the connection |
options.protocols? | Array<'soap' | 'wasm'> | - | The list of protocols to use |
Returns
UseWebSocketReturn
Type declaration
typescript
export type UseWebSocketUrl = (() => string) | string;
export interface UseWebSocketOptions {
protocols?: Array<'soap' | 'wasm'>;
retry?: boolean | number;
onConnected?: (webSocket: WebSocket) => void;
onDisconnected?: (event: CloseEvent, webSocket: WebSocket) => void;
onError?: (event: Event, webSocket: WebSocket) => void;
onMessage?: (event: MessageEvent, webSocket: WebSocket) => void;
}
export type UseWebSocketStatus = 'connected' | 'connecting' | 'disconnected' | 'failed';
export interface UseWebSocketReturn {
client?: WebSocket;
close: WebSocket['close'];
send: WebSocket['send'];
status: UseWebSocketStatus;
open: () => void;
}
Source
Source • DemoContributors
D
H
А