It is a store for socket.io-client. It makes it easy to use socket.io client. It inspired from Redux.
This package has a peer dependency on socket.io-client. if you didn't install it, you should install it first.
With npm
npm install socket.io-client
With yarn
yarn add socket.io-client
With npm
npm install socket.io-client-store
With yarn
yarn add socket.io-client-store
Socket
is socket.io/client
instance.
const socket = io('https://your.socket.io.server.com');
SocketIoStore
get three Arguments.
socket
: Socket instanceMessageHandler[]
: Reducer list for socket.io- it is Object that has
key
,reducer
,state
.key
: stringreducer
: (state, newData) => statestate
: any (initial state)
- it is Object that has
options
: storeOptions
const store = new SocketIoStore(socket: Socket, [{
key: 'chat',
reducer: ( prevState, newData ) => {
// What you want to do with the prevState and newData
return [newState, ...prevState];
}
state: []
}]: MessageHandler[],
{
onConnect: () => {
// What you want to do when connected
},
onDisconnect: () => {
// What you want to do when disconnected
},
onConnectError: () => {
// What you want to do when connection error
},
} : {
onConnect?: () => void,
onDisconnect?: () => void,
onConnectError?: () => void,
});
);
/**
* How to get a state of the key
* @param {string} key - key of the state
* @return {any} - state
*/
const state = store.getState('chat'); // ex) ['hello', 'world', 'hello world']
/**
* How to get Socket instance
* @return {Socket} - socket.io instance */
const socket = store.getSocket(); // ex)
/**
* How to Subscribe, Unsubscribe
* @param {string} key - for you want to subscribe
* @param {Function} callbackFunction - that will be called when state is changed
* @return {Function} - unsubscribe function that can use to remove subscription
*/
const unsubscribe = store.subscribe('chat', (state) => {
// What you want to do with the state
});
/** unsubscribe */
unsubscribe();
/**
* How to send message to server
* @param {string} key - event name
* @param {any} data - data that you want to send
*/
store.send('chat', 'Hello World');
/**
* How to create send function with key
* @param {string} key - event name
* @return {Function} send function that can use to send message
*/
const send = store.createSender('chat');
send('Hello World'); // same as store.send('chat', 'Hello World');
Contributions, issues and feature requests are welcome!