Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redux socket middleware example usage
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)
@ifeanyidavid

This comment has been minimized.

Copy link

ifeanyidavid commented Sep 12, 2018

Hi Mark, thanks for this. This has worked for me so far but I noticed that the socket instance gets created as soon as the application starts including during Login.

How do I create a socket instance only when a user has logged in?

Thank you.

@jon64digital

This comment has been minimized.

Copy link

jon64digital commented Sep 16, 2018

@alaboudi

This comment has been minimized.

Copy link

alaboudi commented Dec 3, 2018

Can you explain why you'd rather create a web socket connection as a middleware rather than capturing it in a side-effect handler?

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