Skip to content

Instantly share code, notes, and snippets.

@acodesmith
Created March 28, 2018 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acodesmith/7cb59ad0ae5c773a010b5bb654282970 to your computer and use it in GitHub Desktop.
Save acodesmith/7cb59ad0ae5c773a010b5bb654282970 to your computer and use it in GitHub Desktop.
Redux middleware for SignalR websocket library.
import * as types from './state/types';
import { signalRAction } from './MessageHandler';
import {
signalRStart,
signalRTrackErrors,
signalRStop,
connection,
} from './Connection';
/**
* Redux Middleware for SignalR
* https://redux.js.org/advanced/middleware
*
* Curried function used in store.js
*
* hubProxy must have an event established before signalRStart is called.
*
* @param {*} hubProxy
*/
export function signalRMiddleware(hubProxy) {
return store => {
const { dispatch, getState } = store;
/**
* set up event listeners for incoming event
*/
hubProxy.on('message', function(message) {
dispatch(signalRAction(message));
});
return next => action => {
if (action.signalR) {
switch (action.type) {
case types.SIGNALR_CONNECT:
signalRStart(connection, hubProxy, dispatch, getState);
signalRTrackErrors(connection, dispatch);
break;
case types.SIGNALR_DISCONNECT:
signalRStop(connection, dispatch);
break;
case types.SIGNALR_INVOKE_MESSAGE:
hubProxy.invoke(action.payload.event, action.payload.payload);
break;
default:
//Do nothing?
}
}
return next(action);
};
};
}
@efstathiosntonas
Copy link

Thanks for the gist, can you share the exportet functions from Connection and the Signalr function?

I m struggling with my setup, signalr onconnected isnt always firing even tho it appears in the eventstream. It seems it fires too fast and react cant catch the event from the signalr server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment