react-ws-wrapper
v1.0.1
Published
The websocket provider to centralized the ws connection & data distribution to the component that listen to the data
Downloads
2
Readme
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!