Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Socket.io not emitting the current state of an array to client side

I’m trying to emit an array of objects to client side using socket.io with node.js (& express)in a React app. When you console.log the array on server side it shows the updated array but when you send the same array to client side its shows the previous state of the array.

Server side:


    let onlineUsers = [];

    const addNewUser = (username, socketId) => {
    !onlineUsers.includes((user) => user.username) &&
    onlineUsers.push({ username, socketId });
    };

    io.on('connection', socket => {

    socket.on("newUser", (username) => {
      addNewUser(username, socket.id);
        console.log(onlineUsers)
      });
    
      socket.emit("allUsers", onlineUsers);```

    Client side: 

    ```     socket.current.emit('newUser', user);
        socket.current.on("allUsers", onlineUsers => {
        // setAllusers(users);
        console.log(onlineUsers);
        })```

     The onlineUsers array here records username of each user on login. Why is it not emitting the current state of the array to client side? Thanks in advance if anyone could help. Please comment if need more info. 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is on the server where you are emitting the data before it’s added by the addNewUser() function, so it will send the old values.

You have to send the data after it’s added.

Example

socket.on("newUser", (username) => {
  addNewUser(username, socket.id);
  console.log(onlineUsers)
  socket.emit("allUsers", onlineUsers);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading