Reputation: 5940
In my react app, I set up a connection to a specific room based on a roomId parameter:
componentDidMount() {
const roomId = window.location.search.replace('?roomId=', '');
this.setState({ roomId });
this.socket = io();
if (!this.socket.socket) {
this.socket.connect();
}
this.socket.on('connect', () => {
console.log(this.state.roomId);
this.socket.emit('room', this.state.roomId);
});
this.socket.on('message', this.handleMessage)
}
Now on my server.js I join and listen for messages like this:
io.on('connection', socket => {
socket.on('room', function(room) {
socket.join(room);
});
socket.on('message', function(data) {
socket.to(data.roomId).emit(data);
});
});
But when I send a message, the other browser window connected to the same roomId does not receive any messages:
const message = {
roomId: this.state.roomId,
value: this.state.field,
};
this.socket.emit('message', message);
I listen for messages like this:
this.socket.on('message', this.handleMessage)
where handleMessage simply sets the state with the new message.
Can anyone see why not?
UPDATE: Here is more of the code to see: https://jsbin.com/pakeyavefo/edit?html,js,output
Upvotes: 0
Views: 395
Reputation: 707976
When you do this:
socket.to(data.roomId).emit(data);
You need to send both a message name and some data. You aren't sending a message name, therefore that event (if it even gets sent) won't match any listeners on the client. Perhaps this is supposed to be:
socket.to(data.roomId).emit('message', data);
Upvotes: 1