i want to write a game Lobby for a card game. Using React.js, Node.js and Websocket.io for achieving this. As so far all went fine. Players are connected in the same Lobby. But i want to print in the Lobby sth Like (Player 1: Steven, Player 2: Frank, ...). I ended up in an infinite loop, i am trying to solve since hours. So maybe someone can help me. It keeps re-rendering by useState i guess, but i don't know how to prevent it from.
Relevant Frontend Code:
const Lobby = (props) => {
const socket = props.socket;
const player = {
room: props.room,
name: props.name,
};
const [playerList, setPlayerList] = useState([]);
socket.emit("joined_lobby", player);
console.log(`${playerList}`);
useEffect(() => {
socket.on("add_user", (data) => {
setPlayerList([...playerList, data.name]);
});
}, []);
Relevant Server Code:
io.on("connection", (socket) => { console.log(`Player with ID:\[${socket.id}\] Connected`);
socket.on("join_room", (data) => {
socket.join(data);
console.log(`Player with ID:\[${socket.id}\] Joined the room ${data}`); });
socket.on("joined_lobby", (data) => {
socket.to(data.room).emit("add_user", data); });
socket.on("disconnect", () => {
console.log(`Player with ID:\[${socket.id}\] Disonnected`); }); });
i would like to say i am currently passing through quite the same challenge, looking out for the solution
Sounds like you only want to run socket.emit("joined_lobby", player); once per 'player'.
If so, move it into a useEffect, and make it so it runs only if the room or player name changes.
useEffect(() => {
const player = {
room: props.room,
name: props.name,
};
socket.emit("joined_lobby", player);
return () => {
// I invented this - you need a way of dealing with leaving
// e.g. if the room changes
socket.emit("left_lobby", player);
}
},[props.room, props.name]);
EDIT: you may need to put props.socket in the deps too - I don't know how the lifecycle of that one works