user3836484
user3836484

Reputation: 205

Socket io.emit to affect React-Redux state

I have set up React + Redux and added socket.io to it. At an UI input box, when I type something, I can pass it to action, then socket, then emit the signal to all browsers visiting that page.

I know io.on('action', data => console.log(data)) is the way for each browser to receive the signal broadcast by socket. But if I wish to use this signal to update the state at each browser, shall I place it at the action file or the redux file?

code to apply:

io.on('action', data => console.log(data)) //will write something to update the state

action file extract:

export const handleNameInput = (name) => {
    return {
        type: InviteeActionTypes.ADD_HANDLENAMEINPUT,
        meta: {remote: true},
        name
    };
}

redux file extract:

case InviteeActionTypes.ADD_HANDLENAMEINPUT: {
    return {
        ...state,
        pendingGuest : action.name
    };
}

server file code:

var http = require('http');
var server = http.createServer();
var socket_io = require('socket.io');
server.listen(4000);
var io = socket_io();
io.attach(server);
io.on('connection', function(socket){
    console.log("Socket connected: " + socket.id);
    socket.on('action', (action) => {
        if(action.type === 'invitee/ADD_HANDLENAMEINPUT'){
            console.log('Data : ', action.name);
            io.local.emit('action', {type:'message', data:action.name});
        }
    });
});

Upvotes: 1

Views: 1768

Answers (2)

Emanuele Pavanello
Emanuele Pavanello

Reputation: 873

For the socket.io integration I suggest to using my two redux middlewares that allows you to subscribe events and emit messages using the redux paradigm.

socket.io-emitter-middleware

socket.io-subscriber-middleware

You can install them via the following commands

npm i socket.io-emitter-middleware

npm i socket.io-subscriber-middleware

and following the README from github documentation for the usage.

In this way you are able to connect your component with redux and susbscribe/unsubscribe events or emit messages by dispatching redux actions.

Upvotes: 0

Dane
Dane

Reputation: 9582

Place the socket.on inside the componentDidMount of the component you wish. And connect the component with Redux ( using react-redux' connect ). Dispatch the action with the socket data.
Something like this:

this.socket.on('action', (action) => {
  this.props.sendDispatch(action);
});

and in your mapDispatchToProps:

const mapDispatchToProps = (dispatch) => ({
  sendDispatch: (action) => {
    dispatch(anyActionCreator(action));  // this action must update your state via reducer
  }
});

export default connect(mapStateToProps, mapDispatchToProps)(YourComponent);

Upvotes: 0

Related Questions