How can my socket stay in a room, so the client will recieve messages

Viewed 65

I'm building a small game in React with Socket.io and Node. But I encountered an issue where the client does not recieve any messages sent to the room. I use the following code in the Node.js server:

Server

app.js

  io.on("connection", (socket) => {
    initGame(io, socket);
  });

game.js

exports.initGame = function (sio, socket) {
  socket.on("joinGameRoom", joinGameRoom);
  socket.on("logSocket", logSocket);
};

function logSocket() {
  let sock = this;
  console.log(sock.rooms);
}

async function joinGameRoom(data) {
  let sock = this;
  let game = data.game;

  await sock.join(String(game._id));
  await sock.in(String(game._id)).emit("playerJoined", game);
  await sock.emit("game", game);
}

Client

game.js

socket.on("playerJoined", (data) => {
  setGame(() => data);
  console.log("player joined!");
});

The listener in the client/game.js is never called. And when I call LogSocket, the only room the socket is in; is it's own room. But other calls have been getting called; calls like "game" :

Client

game.js

socket.on("game", (data) => {
  setGame(() => data);
  console.log("game Call");
});

So my question is: what is it that I'm doing wrong here? Why did my socket leave the room on it's own?

2 Answers

So my problem had to do with React.

I connected in my React client with the socket in a useEffect() hook. This hook made my component rerender on the connect call; which made the component get a new socket every rerender. So the room the socket had joined earlier was still there but the client had a new socket.

So I solved this by initiating the socket in the top component and pass it to with React.Context.

This is not an answer, but I would need to have more stack points to simply add a comment so that is why I post here instead. Do I understand you correctly that you used useContext to listen to events in your top component (for example App.js) in your frontend. And passed the socket listener on via ThemeContext to your children components (game.js etc.)?

Related