Phoenix Auth Liveview Current User

I have been playing around with the new Phoenix Auth generator (https://github.com/aaronrenner/phx_gen_auth) and have been learning a lot just reading through the design/code of the files generated so thank you to anyone who worked on it, impressive! My question is what are the best practices for working with the current user in a liveview .ex file.

When using live view I often want to display a list of items that belong to a certain user. In my item context I have a function set up to talk to ecto and list out items that are associated with a certain user_id.
Items.list_user_items(user) for example.

In order to get the user to feed the function I have found this following code works in the mount call.

def mount(_params, session, socket) do
    user = Accounts.get_user_by_session_token(session["user_token"])
    {:ok, assign(socket, :items, Items.list_user_items(user))}
 end

However in a function like handle_event that does not have the session, how would I properly pass the current user to the list_user_items function?

  def handle_event("delete", %{"id" => id}, socket) do
    item = Items.get_item!(id)
    {:ok, _} = Items.delete_item(item)
    {:noreply, assign(socket, :items, Items.list_user_items(**user**))}
  end
1 Like

:wave:

You’d probably store the current_user in assigns in mount so that it’s accessible at socket.assigns.current_user in other callbacks like handle_event.

You can also create a helper like assign_mount in which you’d assign the user to the socket if you need it in more than one liveivew.

9 Likes

Ha that might have been the quickest answer, kind of embarrassed that didn’t occur to me.

Thank you so much for that link, that page is EXACTLY what I need!

2 Likes

For those who can’t find the page linked by @idi527, it got moved to its own page.

2 Likes

And here’s that same link without the version specified (so it defaults to “latest”)

2 Likes