0
import ...
let socket;

const Game = () => {
const ...

  const [userCount, setUserCount] = useState(0);
  

  const scrollToBottom = () => {
    endToMessages.current?.scrollIntoView({ behavior: "smooth" });
  };

  const { _id, username } = JSON.parse(localStorage.getItem("user")).user;

  useEffect(() => {
    socket = io(process.env.REACT_APP_BASE_URL);
    socket.emit("game_lobby", { id: _id, username, room: gameInfo.name });

    return () => socket.disconnect();
  }, [_id, username, gameInfo.name]);

  useEffect(() => {
    socket.on("message", ({ user, text }) => {
      setMessages((prev) => [...prev, { user, text }]);
      scrollToBottom();
    });

    socket.on("user_count",({count}) => {
      setUserCount(count);
    })

  }, []);

  console.log("Current user count",userCount);

  const sendMessage = () => {
    ...
  };


  return (
    <div className="game section">
       ...
    </div>
  );
};

export default Game;

Server side:

import { Server } from "socket.io";

const socketApi = (server) => {
  const io = new Server(server, {
    cors: {
      origin: ["https://mook-f2b4e.web.app", "http://localhost:3000"],
      methods: ["GET", "POST"],
    },
  });

  io.on("connection", (socket) => {
    socket.on("disconnect", () => {
      console.log(`user ${socket.id} had left`);
    });

    socket.on("game_lobby", async ({ id, username, room }) => {
      console.log("We have a new connetion.");
      socket.join(room);

      const roomClients = await (await io.in(room).fetchSockets()).length;
      console.log(roomClients);
      io.to(room).emit("user_count", { count: roomClients });

      socket.on("disconnect", () => {
        io.to(room).emit("user_count", { count: roomClients });

      });

      
      socket.emit("message", {
        user: "Admin",
        text: `${username} welcome to ${room} room`,
      });
    });

    socket.on("send_message", ({ name, message, room }) => {
      io.to(room).emit("message", { user: name, text: message });
    });
  });

  return io;
};

export default socketApi;

Hi all.When I try to get user count when component mount but I can't.First time when component did mount I get 0 value. If someone else joins the room then I can get its current value. If I could explain properly I mean let's say there are 3 people in the room and I joined that room later. Now there are 4 people in the room but I got 0 value from console.log("Current user count", userCount) if the 5th person joins the room then I can get the current value from the server.

Heartbit
  • 1,698
  • 2
  • 14
  • 26
Umut Palabiyik
  • 313
  • 6
  • 16

1 Answers1

0

I believe you would need the server to have a variable to keep track of active users. So connection increment a variable for onlineUsers, then on disconnect subtract one from the onlineUsers

See reference here => https://stackoverflow.com/a/10276446/3124019

Rguarascia
  • 193
  • 3
  • 20