Skip to content

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 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 jon64digital commented Sep 16, 2018

@alaboudi

This comment has been minimized.

Copy link

@alaboudi 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?

@tienduchust

This comment has been minimized.

Copy link

@tienduchust tienduchust commented Dec 21, 2019

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

That avoid socket connection affect by component life cycle

@ulou

This comment has been minimized.

Copy link

@ulou ulou commented Nov 20, 2020

Hey, thanks for this example, it helped me a lot. However, sometimes you can get error cause message cannot be send during socket connection. To avoid this I add folowing function:

function waitForSocketConnection(socket, callback) {
  setTimeout(
    function () {
      if (socket.readyState === 1) {
        if (callback != null) {
          callback();
        }
      } else {
        console.log("waiting for socket connection...")
        waitForSocketConnection(socket, callback);
      }
    }, 100)
}

and then I replaced line 14 of you code with:

 waitForSocketConnection(socket, () => {
        socket.send(action.payload);
 })

Thanks to this approach we are not blocking redux, however if anyone wants to wait for msg, then we can await waitForSocketConnection(socket, () => {...})

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