-
Notifications
You must be signed in to change notification settings - Fork 2
[State] Handling Native Socket.io Events
State events are events triggered by socket.io, not by user actions. These include: connect
, connect_error
, connect_timeout
, reconnect
, reconnect_attempt
, reconnecting
, reconnect_error
, reconnect_failed
, disconnect
, and error
. These follow a similar format to client events, except an additional function must be added to a chain to retain parameters.
An array of events should be provided to the middleware, with each event being an object comprised of:
- An action property
- A dispatch function
Where the action is a string, "event", from one of socket.io's native events. See a list of these events here.
The first function chain for dispatch accepts 4 parameters in the following order:
- A reference to the original socket
- The current store
- The "next" function
- The action being emitted
The last function in the chain will be comprised of a maximum of 1 parameter corresponding to the call made by socket.io. For example, the connect
action has no parameters, but reconnecting
takes in one parameter -- the number of attempts
import * as socketMiddleware from 'socket.io-middleware';
const action = 'reconnecting';
const dispatch = (socket, store, next, action) => (attemptNumber) => {
console.log('Socket is reconnecting', action, attemptNumber);
};
const COUNTER_RECONNECTING_EVENT = {
action,
dispatch,
};
socketMiddleware.socketio( null, [], [], [ COUNTER_RECONNECTING_EVENT ], "COUNTER_MIDDLEWARE" );
Due to the default nature of this library, having multiple sockets, a client event has to be emitted to disconnect the socket; otherwise the middleware won't know which socket to disconnect.
We create a redux action to emit the disconnect event
import { createAction } from 'redux-actions';
export const actions = {
COUNTER_MIDDLEWARE_DISCONNECT: createAction('COUNTER_MIDDLEWARE_DISCONNECT'),
};
And the middleware will disconnect the socket. A disconnect
state event can also be added to capture when the socket is disconnected.