Last active
November 7, 2017 21:22
-
-
Save AlexChittock/4a7e4883c1c17e02159e1c1859b8726f to your computer and use it in GitHub Desktop.
Middleware for Redux that routes actions to and from a server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createSocketMiddleware } from 'redux-socket-middleware' | |
const store = createStore( | |
reducer, | |
applyMiddleware( | |
createSocketMiddleware((action) => store.dispatch(action), 'http://localhost:3030') | |
) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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