Skip to content

Instantly share code, notes, and snippets.

@AlexChittock
Last active November 7, 2017 21:22
Show Gist options
  • Save AlexChittock/4a7e4883c1c17e02159e1c1859b8726f to your computer and use it in GitHub Desktop.
Save AlexChittock/4a7e4883c1c17e02159e1c1859b8726f to your computer and use it in GitHub Desktop.
Middleware for Redux that routes actions to and from a server
import { createSocketMiddleware } from 'redux-socket-middleware'
const store = createStore(
reducer,
applyMiddleware(
createSocketMiddleware((action) => store.dispatch(action), 'http://localhost:3030')
)
)
import io from 'socket.io-client'
const getMiddleware = (socket) => (store) => (next) => (action) => {
socket.emit('action', action)
return next(action)
}
const bindDispatch = (socket, dispatch) => {
socket.on('action', (action) => {
!action.remote && dispatch(Object.assign({}, action, {remote: true}))
})
}
const init = (socket) => socket.emit('init')
export const createSocketMiddleware = (dispatch, url = null, preload = true) => {
const socket = io.connect(url)
bindDispatch(socket, dispatch)
preload && init(socket)
return getMiddleware(socket)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment