Home > Software engineering >  Socket.io not emitting the current state of an array to client side
Socket.io not emitting the current state of an array to client side

Time:02-02

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. 

CodePudding user response:

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.

Send the data inside the socket message listener, after it's added to the array.

Example

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