Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

64
Views
Problem with creating online user list with socket.io and React

I am trying to add a list of online users to my chat app, but I ran into this problem:

On the front end I emit the currently logged in user's name, and then update the state of my users array:

useEffect(() => {
    if (Auth.loggedIn()) {
      const { data } = Auth.getUserInfo();
      socket.emit("user_connected", data.username);
    }
// if I remove these brackets I get an infinite loop in my server
  }, []);

 useEffect(() => {
    socket.on("online_users", (onlineUsers) => {
      setUsers(onlineUsers);
      console.log(users);
    });
  });

I created the user array in the back end using the emitted username:

const onlineUsers = [];
io.on("connection", (socket) => {
  socket.join("public_chat");
  console.log(`A user has joined the chat`);

  socket.on("user_connected", (user) => {
    const userExists = checkUserArray(user, onlineUsers);
    if (!userExists) {
      onlineUsers.push({ user, id: socket.id });
    }
    console.log(onlineUsers);
    socket.in("public_chat").emit("online_users", onlineUsers);

    console.log(`${user} is now online.`);
  });
});

I opened two separate browsers with two different logged in users to test, and when I refresh the page on one browser, the other gets the updated online user list in real-time, but the browser I initially refreshed on has an empty array for the user state. Do I need to make a global state store using redux or something?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!