darmawan01 / react-ws-wrapper

A websocket utilities to handle websocket connection & subscription

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React Websocket Wrapper

This package was fit combined with this Golang ws-wrapper package.

Installation

npm i react-ws-wrapper

Wrap your component

import WebSocketProvider from '@/context/WebsocketContext';
import { ChildComponent } from './child';

export function App() {
  return (
    <div>
      <WebSocketProvider url={new URL('ws://localhost:3000')}>
        <h1>Hello World</h1>

        <ChildComponent />
      </WebSocketProvider>
    </div>
  );
}

Use the hooks

import { useWebSocket } from '@/hooks/useWebsocket';
import { useEffect } from 'react';

export function ChildComponent() {

  const { state, subscribes } = useWebSocket();

  useEffect(() => {
    let unsubscribes = () => { };
    if (state.isConnected) {
      unsubscribes = subscribes([
        { chan: { name: 'test', }, cb: onData },
      ]);
    }
    return () => {
      unsubscribes();
    };
  }, [state]);

  const onData = (data: unknown) => {
    console.log(data);
  };


  return (
    <div>
      <h1>Hello World</h1>
    </div>
  );
}

See the example for more detail!

About

A websocket utilities to handle websocket connection & subscription

License:Apache License 2.0


Languages

Language:TypeScript 100.0%