In this episode, we tackle the challenge of keeping our online users list up-to-date in real time. Initially, we were only grabbing a list of online users once, which doesn't react to people joining or leaving—so it quickly got out of sync. We start off by hooking into the user presence events on our channel, specifically listening for when users join or leave.
We clean up our code a bit and add listeners for the join and leave events. Next, we jump into our user store to add two actions: one for adding a user and another for removing a user. We make sure that when a new user joins, we only add them if they don’t already exist in our list, to avoid duplicates. When someone leaves, we filter them out of our users array.
Then, we test things out, but run into a subtle problem—because we’re using Inertia, the user can stay in the channel even after “navigating away,” so our users list doesn’t update as it should. To fix this, we use the Vue onUnmounted
lifecycle hook to properly leave the channel when our room component unmounts. This totally solves the syncing problem!
By the end, we’ve got a system that reliably adds and removes users from the online list in real time, even as people navigate around the app. This makes the user presence feature much more robust and, most importantly, always in sync with reality.