-
Notifications
You must be signed in to change notification settings - Fork 2
[Client] Emitting Events to the Server
Client Events are events sent from the client (web browser) to the server. 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 unique string, "event", to be dispatched from Redux.
The dispatch function accepts three parameters in the following order:
- A reference to the socket
- The Redux store
- The action sent from redux
import * as socketMiddleware from 'socket.io-middleware';
const dispatch = (socket, store, action) => {
// dispatch an action with the store to the server
socket.emit(action.type, action.payload);
};
const COUNTER_CHECK_CLIENT_VERSION_EVENT = {
action: "COUNTER_CHECK_CLIENT_VERSION",
dispatch,
};
socketMiddleware.socketio( null, [ COUNTER_CHECK_CLIENT_VERSION_EVENT ], [], [], "COUNTER_MIDDLEWARE" );
To emit an event to the server, you first need to set up a Redux action that will be handled by the middleware:
import { createAction } from 'redux-actions';
export const actions = {
COUNTER_CHECK_CLIENT_VERSION_EVENT: createAction('COUNTER_CHECK_CLIENT_VERSION_EVENT', (version) => {
return {
version,
};
}),
};
This action, needs a corresponding "client" event within the middleware:
const dispatch = (socket, store, action) => {
socket.emit(action.type, action.payload);
};
export default {
action: 'COUNTER_CHECK_CLIENT_VERSION_EVENT',
dispatch,
};
Within your application, you can then call
import { actions } from './actions';
// store is the redux store instance
store.dispatch(actions.COUNTER_CHECK_CLIENT_VERSION_EVENT('my-client-version'));
and the server will receive an COUNTER_CHECK_CLIENT_VERSION_EVENT
with an object containing a version
property.
Most client events to be emitted to the server will follow the same structure:
const dispatch = (socket, store, action) => {
// dispatch an action with the store to the server
socket.emit(action.type, action.payload);
};
To avoid code duplication, the middleware provides a default function handler identical to the one above. This function will execute when the dispatch property is missing from the export:
export default {
action: 'COUNTER_CHECK_CLIENT_VERSION_EVENT'
};