Forked from markerikson/redux-socket-middleware-example.js
Created
June 17, 2019 08:06
-
-
Save EmperorEarth/53dd0ac823129bb02d7970168380d858 to your computer and use it in GitHub Desktop.
Redux socket middleware example usage
This file contains 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
const createMySocketMiddleware = (url) => { | |
return storeAPI => { | |
let socket = createMyWebsocket(url); | |
socket.on("message", (message) => { | |
storeAPI.dispatch({ | |
type : "SOCKET_MESSAGE_RECEIVED", | |
payload : message | |
}); | |
}); | |
return next => action => { | |
if(action.type == "SEND_WEBSOCKET_MESSAGE") { | |
socket.send(action.payload); | |
return; | |
} | |
return next(action); | |
} | |
} | |
} | |
// later, in your app | |
function sendSocketMessage(message) { | |
return { | |
type : "SEND_WEBSOCKET_MESSAGE", | |
payload : message | |
} | |
} | |
class MyComponent extends React.Component { | |
handleClick = () => { | |
this.props.sendSocketMessage("This goes to the server"); | |
} | |
} | |
export default connect(null, {sendSocketMessage})(MyComponent) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment