Skip to content

A websocket utilities to handle websocket connection & subscription

License

Notifications You must be signed in to change notification settings

darmawan01/react-ws-wrapper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published