Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

71
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda