How to pass data from a plug into into a LiveView, to every single one at once?

On the normal pages in a project I’m using data that gets loaded from a plug. A plug looks like this:

defmodule WebApp1.Plug1 do
  import Plug.Conn

  def init(options) do

  # simplified
  def call(conn, _opts) do
    data1_id = get_session(conn, :data1_id)
    data1 = get_data1_from_db(data1_id)
    assign(conn, :data1, data1)

Now that I’m rewritting some page to LiveView, I’ve bumped into an error that data1 has become unavailable in a app layout in which it – data1 – is getting used.

How to fix this?
How make data1 accessible in not a single live view but all the ones that I have and will?

I’m aware of this elixir - How to pass plug loaded data to LiveView components - Stack Overflow

but it suggest that one will have to refer to a session in every single live view from on. Isn’t there a better way?

Following the above link, I think you’re looking for on_mount which’ll allow you to load in data1 into your socket.assigns for every liveview, through live_session

Check out this livebook hook and its router as an example to work off of.

I know how to load it in “on_mount” of a single live view.

“How will I make data1 accessible in not a single live view but in all the ones that I have and will?”

Namely, without having to copy-paste the same code into each live view – the same way a plug would work

You must read through the Security Considerations first, then you can use the :on_mount option of the live_session macro in your router to mount lifecycle hooks on all routes in the live_session block.

1 Like