Using Websockets with Redux

October 25, 2017β€’1 min read

Redux is new the cool kid out there in the Flux frameworks town.

Update : I've just created a new repo with a project that implements the principles I exposed in the article πŸ˜‰

What makes its strength is the concept of pushing all the side-effects to the edges of your program and using functions called actions to mutate a single atom representing the whole state of your app.

Websocket communication is one kind of side-effect.

Here is a workaround I came with when I needed to add a Websocket-based chat inside a Redux app.

Let's first create what we can call a 'business object'.

It will live next to the redux store inside main.js :

const SocketObject = {
  ws: null,
  startWS,
  stopWS,
  wsDipatcher,
  wsListener
};

This SocketObject has 4 functions : to bootstrap a websocket, to kill a websocket, listen to actions, and dispatch some actions

function wsListener() {
  const { session, lastAction } = store.getState()
  switch (lastAction.type) {
    case POST_MESSAGE:
      return sock.ws.postMessage(
          lastAction.text,
          lastAction.fromID,
          lastAction.toID
        )

    case AUTH_CONNECTED:
      return sock.startWS(session)

    case AUTH_DISCONNECTED:
      return sock.stopWS()

    default:
      return
  }
}
function wsDipatcher (msg) {
  const { getState, dispatch } = store
  const { session } = getState()
  return dispatch(ChatActions.receiveEvent(msg, session))
}
function startWS(session) {
  if(!!sock.ws) { sock.ws.close() }
  if(session.token){
    sock.ws = new WebsocketInstance(URL, session.token, sock.wsDipatcher)
  }
}
function stopWS(session) {
  if(!!sock.ws) { sock.ws.close() }
}

We need to attach the SocketObject to the redux store.

store.subscribe(() => SocketObject.wsListener())

PS : This approach has shortcomings when dealing with redux-devtools because redux-devtools replays all your actions stored when you enable/disable them in the interface. Every action after the toggled one will be played twice or more because the websocket connection is stateful.



author undefined

By Yannick Spark : a Front-end engineer who works remotely at Teacup Analytics.
He likes Functional programming, Nutrition & Fasting, and Remote work.
You should definitely on Twitter πŸ‘‹