In this episode, we're tackling the issue of keeping our user list up to date in real time when folks join or leave a room. Previously, we set things up so that when the page loads, we get a list of users currently in the room, but there wasn't anything in place to handle changes as people come and go. Time to fix that!
First up, we add a new event to handle when a user joins. We write a method that listens for the join event, grabs the new user's info, and pushes their ID to our presence list. We then test it out: when someone jumps into the room, they're added to the list immediately, and we can see that in action.
Next, we handle users leaving. This is a bit trickier because instead of adding, we need to remove the user from our array. We use PHP's array filtering to create a new list that leaves out the departing user's ID—making sure our condition is set correctly so we don't remove the wrong one!
Finally, we test that leaving works as expected. After fixing a small logic bug (using !=
rather than ==
), users are properly removed from the list. With those tweaks, our users list now updates in real-time whenever someone joins or leaves, giving us a much better and more dynamic experience.