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

hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
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
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
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
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52774 488
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
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
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

We're in Beta

About us Mission Statement