Skip to content

Instantly share code, notes, and snippets.

@hprobotic
Last active December 7, 2016 08:11
Show Gist options
  • Save hprobotic/7e23139ffda330371ae49894658f1b31 to your computer and use it in GitHub Desktop.
Save hprobotic/7e23139ffda330371ae49894658f1b31 to your computer and use it in GitHub Desktop.
Socket Handler for Redux and React
//In socket file
const io = require('socket.io-client')
const SOCKET_IO_MESSAGE = 'SOCKET_IO_MESSAGE';
var socket = io('http://localhost:8000/')
export default function attachListener(func) {
//Return a thunk, so that we can access dispatch
return function(dispatch) {
//We're passing dispatch into our listener so that it can dispatch events to redux.
socket.on('data', func(dispatch));
}
}
//In our listener action creator
function listener(dispatch) {
//This function is the actual event handler which will receive socket data.
return function(data) {
dispatch({
type: SOCKET_IO_MESSAGE,
message: data
});
//Attach any custom handler code here.
}
}
//Register the listener somewhere in the application by dispatching the `attachListener` action.
class MyComponent extends Component {
componentWillMount() {
this.props.init();
}
}
connect(
null,
dispatch => ({
init: () => dispatch(attachListener(listener))
})
)(MyComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment