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

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39523 209
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36432 110
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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

We're in Beta

About us Mission Statement