@reactivers/hooks Github link@reactivers/hooks NPM link

useSocket

Introduction

  • useSocket is an awesome socket manager.
  • You can track web socket connections on a single state or connect anywhere easily
const { 
    connect,
    lastData, 
    readyState, 
    sendData, 
    socket 
} = useSocket({ 
    url, 
    wss,
    disconnectOnUnmount
});

Getting Started

  • You need to import useSocket and SocketProvider.

From Collection

import { useSocket, SocketProvider } from "@reactivers/hooks";

From Package

import { useSocket, SocketProvider } from "@reactivers/use-socket";

Interfaces

Provider

export interface SocketProps {
    /* If you want to use a single url for your sockets
        you can pass your url to the provider
    */
    url?: string;
    /* If you want to use secure url for your sockets
        you can set it via the provider
    */
    wss?: boolean;
    /* If you want disconnect all sockets on unmount
        you can set it via the provider
    */
    disconnectOnUnmount?: boolean;
}

Hook

// The hook gets the same parameters as the provider
const useSocket: (props?: SocketProps) => SocketResponse

interface SocketResponse extends SocketState {
    connect: (params?: IConnect) => WebSocket;
    socket: WebSocket,
    sendData: (data: any) => void;
}

interface IConnect extends SocketEvents, SocketProps {
    endpoint?: string;
}

interface SocketEvents {
    onOpen?: onOpenFunc,
    onClose?: onCloseFunc,
    onError?: onErrorFunc,
    onMessage?: onMessageFunc
}

declare type onOpenFunc = (data: any) => void;
declare type onCloseFunc = (data: any) => void;
declare type onErrorFunc = (data: any) => void;
declare type onMessageFunc = (data: any, json: any) => void;


interface ISocketContext extends SocketProps {
    connect: (params: { path: string }) => WebSocket
}

interface SocketState {
    readyState: number;
    lastData: any;
}

Example

Example Preview - CodeSandbox