'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. 


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source