socket-redux-middleware
socket-redux-middleware
Redux middleware and a React hook that connect a Socket.IO client to a Redux store: actions emitted by the server are dispatched automatically, and actions matching your own criteria are emitted to the server before continuing through the middleware chain.
Installation
npm install socket-redux-middleware
react, react-redux, redux, and a Socket.IO client instance are peer
dependencies — install/configure them in your app if you haven't already.
Usage
1. Wire up the middleware
import { createStore, applyMiddleware } from "redux";
import io from "socket.io-client";
import { socketIoMiddleware } from "socket-redux-middleware";
import rootReducer from "./reducers";
const socket = io("https://example.com");
const store = createStore(
rootReducer,
applyMiddleware(socketIoMiddleware(socket, ["server/"]))
);
- Actions emitted by the server under the event name
"action"are dispatched into the store automatically. - Actions dispatched on the client whose
typematches thecriteria(a string prefix, an array of prefixes, or a(type, action) => booleanfunction) are emitted to the server viasocket.emitinstead of (or in addition to) being passed down the middleware chain.
2. Dispatch from a component
import { useSocketDispatch } from "socket-redux-middleware";
function Chat() {
const socketDispatch = useSocketDispatch();
const sendMessage = (text) => {
socketDispatch("server/message", { text });
};
return <button onClick={() => sendMessage("hi")}>Send</button>;
}
useSocketDispatch returns a stable callback that dispatches
{ type, payload, keyName, keyType } — pair it with the criteria you gave
socketIoMiddleware so those actions get routed to the server.
API
socketIoMiddleware(socket, criteria, options)
| Param | Type | Default | Description |
|---|---|---|---|
socket |
Socket |
required | A connected Socket.IO client instance. |
criteria |
string | string[] | (type, action) => boolean |
[] |
Selects which dispatched actions get sent to the server. A string/array matches by type prefix. |
options.eventName |
string |
"action" |
Socket.IO event name used both for actions received from the server and actions emitted to it. |
options.execute |
(action, emit, next, dispatch) => any |
emits + calls next(action) |
Override how a matching action is handled instead of the default emit-then-continue behavior. |
useSocketDispatch()
Returns socketDispatch(type, payload, keyName, keyType), a memoized
callback that dispatches { type, payload, keyName, keyType } through
react-redux's useDispatch.
License
MIT