Geov
Geov

Reputation: 87

Socket.emit doesn't trigger for all clients

I am new to react with socket.io, and I am stuck on the retrieving data permanently on frontend. What I'm trying to do is to create a little game and first step is to have a lobby page where multiple users can join.


Here is the part where I have problems because, if example, if I create a game with user Test

Lobby is now just with user Test

Tab1:

| --- Test --- |

But if I open a new tab and join to the current tab with the user Test1, my new tab is

Tab2:

| --- Test Test1 --- |

The problem that I ecounter is that the first tab only have the first user joined in the game

Tab1:

| --- Test --- |

The event didn't trigger for this tab. The same scenario happends for the next tabs and so on.

Node.js code


socket.on("getUsers", async (data) => {
  if (!data.gameCode) {
    universalError("GameCode doesn't exist");
    return;
  }

  const existentGame = await pubClient.get(data.gameCode);

  if (!existentGame) {
    universalError("The Current Game Does Not Exist");
    return;
  }

  currentGame = JSON.parse(existentGame);
  socket.emit("gameUsers", {
    gameUsers: currentGame,
  });
});

React code

const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b); 

function() {
  const socket = useContext(SocketContext);
  const [host, setHost] = useState("");
  const [users, setUsers] = useState([]);

  useEffect(() => {
    if (!currentGameCode) return;

    socket.emit("getUsers", { gameCode: currentGameCode });
  }, []);

  socket.on("gameUsers", (data) => {
    setHost(data.gameUsers.host);

    console.log(users, data.gameUsers.users);

    if (!equals(users, data.gameUsers.users)) {
      setUsers(data.gameUsers.users);
    }
  });

  return(
  ...
  )
}

I tried to put the socket.on before useEffect function, also insert the socket.on inside a useEffect with multiple dependency but I had no success with that. From what I saw, the user enter in socket.on("gameUsers") just once per tab and that is when he join the game.. The call on the backend is made everytime a new user join to the game, but my socket.on doesn't trigger in that case. Any ideas of what I'm doing wrong? Anticipated thanks!

Upvotes: 0

Views: 648

Answers (1)

Geov
Geov

Reputation: 87

Ok, I figured it out, the problem was not on the client side but on server side.. So I edited the title from

Socket.io doesn't trigger event for previous tabs - React

to

Socket.emit doesn't trigger for all clients.


I was trying to emit the event only to the particular socket which triggered the event.

socket.emit < - was triggered JUST by - > socket.on at which was connected to.

SOLUTON: Use io.emit to send to all client

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

Upvotes: 1

Related Questions