iacobson

iacobson

LiveView - passing info from the conn to the socket

Hi,

What would be a good way to pass some information from the conn to the LiveView socket ?
Let’s assume the following example

router.ex

scope "/admin", MyAppWeb.Admin do
  ......
  pipe_through :ensure_admin_authenticated
  live "/article/:id/edit"
end

In my ensure_admin_authenticated plug I check the current user, see if it is admin and assign it to the conn.

I would like to have that available in the LiveView socket. For example, if I render the LiveView from a controller, I can use the session to pass the user, but I would not want to use controllers if possible.

Thanks

Marked As Solved

chrismccord

chrismccord

Creator of Phoenix

You can a combination of assign_new and the session. Assuming your :ensure_admin_authenticated plug places a user_id key in the session, you can tell the live macro in the router to copy the conn session key to the LV session. Then on mount, you can use assign_new to first check the parent assigns for the :current_user, and fallback to lookup from the session. This allows the initial HTTP render to only fetch the user once via your plug. Then when the LV mounts in a connected state from the client, it will fallback to lookup the current_user from the session. For example:

scope "/admin", MyAppWeb.Admin do
  ......
  pipe_through :ensure_admin_authenticated
  live "/article/:id/edit", session: [:user_id]
end

...

def MyLive do

  def mount(%{user_id: user_id}, socket) do
    {:ok, assign_new(socket, :current_user, fn -> lookup_user(user_id) end)}
  end
end
17
Post #2

Also Liked

askasp

askasp

Hi! This does not seem possible anymore after this commit Remove deprecate features · phoenixframework/phoenix_live_view@0020c35 · GitHub Is there a alternative way of achieving the same?

iacobson

iacobson

Thanks Chris !

setting the user_id in the session worked perfectly.

For anybody following this subject, I ended up with a route like
live "/article/:article_id/edit", EditArticleLive, session: [:path_params, :current_user_id]

However, the assign_new only half worked for my case. In your example above it would always lookup_user/1 for me when the LV mounts.

If I inspect the conn, the first iteration would be

%Phoenix.LiveView.Socket{
  assigns: %{
    current_user: %MyApp.Accounts.Schema.User{
      __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
      id: 3,
      ...
    },
    my_text: ""
  },
  changed: %{current_user: true, my_text: true},
  connected?: false,
  endpoint: MyAppWeb.Endpoint,
  fingerprints: {nil, %{}},
  id: "phx-+acWjg8b",
  parent_pid: nil,
  private: %{
    assigned_new: {%{
       current_user: %MyApp.Accounts.Schema.User{
         __meta__: #Ecto.Schema.Metadata<:loaded, "users">,
         id: 3,
         ...
       }
     }, [:current_user]}
  },
  stopped: nil
}

Which looks fine to me.
But then in the second iterations turns into this, if I do not fetch the User

%Phoenix.LiveView.Socket{
  assigns: %{current_user: nil, my_text: ""},
  changed: %{current_user: true, my_text: true},
  connected?: true,
  endpoint: MyAppWeb.Endpoint,
  fingerprints: {nil, %{}},
  id: "phx-noktpWPS",
  parent_pid: nil,
  private: %{assigned_new: {%{}, [:current_user]}},
  stopped: nil
}
mekusigjinn

mekusigjinn

ooh something I might be of help!

# at router.ex:
...
live "/", ThisIsLive #no need to do "session: ..."
...
put_session(conn, :session_id, session_id)

# at LiveView:
...
def mount(_params, session, socket) do
    session_id = session["session_id"]
   # session has whatever you pushed in router, via put_session()
...
end

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

We're in Beta

About us Mission Statement