How to Display User Tracking

Let's learn how to display tracked user data in the Phoenix application.

We’ve come a surprisingly long way with user activity tracking, but there’s still a bit of work to do. We’ll implement a component, UserActivityLive, that will use its update/2 callback to ask Presence for the list of products and their present users. It will store this list in the state with the socket assigns. Then, we’ll render that list in our component’s template.

Let’s kick things off by defining our component.

The user tracking component

To define our component, we create a new file, pento/lib/pento_web/live/user_activity_live.ex, and add in this component definition:

Press + to interact
defmodule PentoWeb.UserActivityLive do
use PentoWeb, :live_component
alias PentoWeb.Presence
def update(_assigns, socket) do
## coming soon!
end
end

We know that the component needs to fetch a list of presences when it first renders. Later, we’ll teach the component to update whenever a new presence is added to the PentoWeb.Presence data store. As we might guess, we’ll have the parent LiveView, AdminDashboardLive, receiving a message when this happens and responding by telling the component to update. So, we want to use the component’s update/2 function on line 5 to fetch the presence list and store it in the state, rather than the mount/3 function. This way we ensure that the presence list is re-fetched when the component updates later on. More on this update flow later. First, we started with building the update/2 function in pento/lib/pento_web/live/user_activity_live.ex like this:

Press + to interact
def update(_assigns, socket) do
{:ok,
socket
|> assign_user_activity()}
end

As usual, we extract the code to build a user activity list to a reducer function called ...