It is for easily using Websocket in React. It inspired by React-redux.
It is provider of socket-store.
#npm
npm install react-socket-store
#yarn
yarn add react-socket-store
MesssageHandler and Socket store is based on socket-store.
First, create a message handler.
Define the topic, callback for the topic, and default status. This will be provided in the store.
- createMessageHandler(key, callback, state)
key
: it will be subject of message.callback
: it will works like reducer. it must return state!state
: it is defualt state.
const talkHandler = createMessageHandler<string[], string>(
"talk",
(state, data) => {
return [...state, data];
},
[]
);
Next, create a socket store.
Store gets two or three parameters for web sockets and message handlers.
WebSocket instance
,array of message handler
,options
options has callbacks about connection status.
- createSocketStore(ws: WebSocket, messageHandlers: MessageHandler[], options?: SocketStoreOptions)
const socketStore = createSocketStore(
new WebSocket("ws://localhost:3000"),
[talkHandler],
{
onOpen: () => console.log("open"),
onClose: () => console.log("close"),
onError: () => console.log("error"),
}
);
- Wrap your
<App>
with<SocketProvider>
, and provide a previously created store as a prop for the socket provider.
import { SocketProvider } from "react-socket-store";
import store from "./store";
const Index = (prop: Props) => {
return (
<SocketProvider store={store}>
<App />
</SocketProvider>
);
};
we supply API for using SocketStore, by hooks.
useSocket
gets the parameter for the key of the MessageHandler, and returns the state, and sendfunction for the key.
const Component = (props: ComponentsProps)=>{
const [value, setValue] = useState('');
const [state, send] = useSocket('talk');
const onChange = (e)=>{
setValue(e.target.value);
}
const submit = (e)=>{
e.preventDefault();
send(value);
}
return (
<>
<div>
{state.map(message)=> <span>{message}</span>}
</div>
<form onSubmit={submit}>
<input value={value} onChange={onChange} />
</form>
</>
)
}
useSend
gets the paramerter for the key of the MessageHandler, and returns
only sendfunction for the key.
const Component = (props: ComponentsProps) => {
const [value, setValue] = useState("");
const [send] = useSend("talk");
const onChange = (e) => {
setValue(e.target.value);
};
const submit = (e) => {
e.preventDefault();
send(value);
};
return (
<>
<form onSubmit={submit}>
<input value={value} onChange={onChange} />
</form>
</>
);
};
useListen
gets the paramerter for the key of the MessageHandler, and returns
only state for the key.
const Component = (props: ComponentsProps) => {
const [state] = useListen("talk");
return(
<div>
{state.map((message)=> <span>{message}</span>)}
</div>
)
};
MIT