title: Socket.io - React: How to display the users connected in a room?
body: <p>I'm trying to map the users connected to my chat app and render them in a div.</p>
  <p>I'm saving the users in an array of objects and emitting an event updating the array when the user connects and disconnects from the chat room in the backend and getting the object in the frontend, saving it in an array and using map to display the users.</p>
  <p>When i map the array to display the users my page just shows the current user and the subsequent users, not showing the previous users connected. For example, if I open the app with the name &quot;Bruce&quot; and another page with the user &quot;Andrew&quot;, the first page will show both users and the second only &quot;Andrew&quot;. If I console.log the array I'm getting from the backend it shows both users. If I exit any page or reload it, it shows &quot;TypeError: Cannot read property 'username' of undefined&quot;</p>
  <p><strong>Backend</strong></p>
  <pre><code>const users = []
  
      // Storing user
      const user = { id, username, room } 
      users.push(user)
  
  const getUsersInRoom = (room) =&gt; {
      return users.filter((user) =&gt; user.room === room)
  }
  
  socket.on('join', ({ username, room }, callback) =&gt; {
      io.to(user.room).emit('roomData', {
        room: user.room,
        users: getUsersInRoom(user.room)
      })
      callback()
    })
  
    socket.on('disconnect', () =&gt; {
        io.to(user.room).emit('roomData', {
          room: user.room,
          users: getUsersInRoom(user.room)
        })
      }
    })
  </code></pre>
  <p><strong>Frontend</strong></p>
  <pre><code>    const [usersName, setUsersName] = useState([]);
  
      useEffect(() =&gt; {
          socket.on('roomData', ({room, users}) =&gt; {
              setUsersName(previousUsersName =&gt; [...previousUsersName, users]);
          })
      },[]);
  
      return (
               &lt;div&gt;
                  {
                      usersName.map((name, i) =&gt; (
                          &lt;div key={i}&gt;
                              &lt;p&gt;
                                  &lt;span&gt;{name[i].username}&lt;/span&gt;
                              &lt;/p&gt;
                          &lt;/div&gt;
                      ))
                  }
                &lt;div/&gt;
  
  </code></pre>
  <p>When I  console.log(usersName) it shows the array in this format:</p>
  <pre><code>[Array(1)]
     0: Array(1)
        0:
           id: &quot;yXXo7TXVHWN1bzl6AAAV&quot;
           room: &quot;Games&quot;
           username: &quot;Bruce&quot;
  </code></pre>
  <p>I believe the backend is correct since I'm getting all users. The problem I think is how i'm mapping the array using &quot;name[i].username&quot; since when I reload the page it breaks it and the page renders the names incorrectly as stated above.</p>
  <p>Any help is appreciated, If it's confusing or I'm missing some data, please let me know.</p>