Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

70
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda