0
votes

In liveview, how can I pass the user data from leex to the context? I have phx.gen.live a profiles context, and I want to add user_id to the profile every time user create the new profile. I change the create_profile code to:

**profiles.ex (context)**
  def create_profile(attrs \\ %{}, userid) do
    attrs = Map.put(attrs, "user_id", userid)
    %Profile{}
    |> Profile.changeset(attrs)
    |> Repo.insert()
  end

I am using pow, so in normal phoenix case, I would just do this:

user = Pow.Plug.current_user(conn) #<-- this is conn
Profiles.create_profile(profile_params, user.id)

but in liveview, instead of conn, it use socket. So I am not sure how to go about it.

1
you can create a plug and pass the user_id through sessionDaniel
IDK if it answers your question but have a look at stackoverflow.com/questions/65357773/… And if you are using standalone components inside any of your controllers you can pass it as session as well hexdocs.pm/phoenix_live_view/…Evaldo Bratti
Thanks for the info. After spending the whole day staring at the code, I finally understand how it works. Anyway, I will read the link when I have time later.sooon

1 Answers

0
votes

There are lots of different ways to do this but I will describe a straightforward approach.

  1. In the function where you "log in" a user, I assume you have access to the conn. I also assume you have a user_token, if you are using Pow. If so, do this:
conn
|> put_session(:user_token, user_token)
  1. Now go to your live_helpers.ex file (or create it if you don't have one) and make a function like this:
  def assign_defaults(session, socket) do
    socket =
      socket
      |> assign_new(:current_user, fn ->
        find_current_user(session)
      end)

    socket
  end
  1. Also, in live_helpers, write this function:
  defp find_current_user(session) do
    with user_token when not is_nil(user_token) <- session["user_token"],
         %User{} = user <- Accounts.get_user_by_session_token(user_token),
         do: user
  end
  1. Now in any LiveView modules where you need to access the current_user, just put this in your mount function:
  def mount(_params, session, socket) do
    socket =
      assign_defaults(session, socket)

    {:ok, socket}
  end

And then you will have access to the session.assigns.current_user.