Created
June 28, 2018 00:37
-
-
Save markerikson/3df1cf5abbac57820a20059287b4be58 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) |
@n-ii-ma looks fine at first glance.
You might want to look at the FAQ entry that describes why we normally recommend that websocket-type connections should go into a middleware:
@markerikson Many thanks Mike!
Upon further consideration and after a conversation with Lenz, I decided to use the listenerMiddleware
, yet I'm still trying to figure out how to stop a particular listener
@n-ii-ma probably best to ask over in #redux
in Reactiflux, but typically you'd dispatch an action and have the listener do an await take(thatAction)
and then cancel itself / return.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@markerikson: Thank you for your response Mark. Well, I've used your example here and on Stackoverflow as a base to configure the Socket
middleware
withSocket IO
andLaravel Echo
in this way and just as the docs recommends I use.concat
to append the middleware to the store:(Each section is in its own file)
Everything is working as expected yet I myself am a bit cautious regarding this method due to the lack of adequate examples and am wondering if it indeed adheres to the Redux standards.
One more question I was wondering about is why is redux requiring the WebSocket connection to be as a middleware and how is RTK Query handling this issue with its Streaming Updates that plain Redux Toolkit is unable to do.