shankardevy

shankardevy

LiveView: Merge assigns from conn to socket

Currently when I assign a value in conn.assigns in the router, the assigned value is not merged with the socket.assigns.

Patching this line https://github.com/phoenixframework/phoenix_live_view/blob/v0.11.1/lib/phoenix_live_view/static.ex#L114 to include the assigns from conn works.

However, I do not understand if there is any reason for not doing this. Also I see the conn.assigns is copied to private.assign_new but don’t understand the purpose.

Anyone having background on this could explain the rationale?

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Live view renders happen twice. There is the first static render that happens as part of an HTTP GET request. The conn is evaluated, a socket built / mounted, the page rendered. After that though the socket goes away entirely, it was just there to address the HTTP get request, there is no persistent connection.

Then the javascript on the page runs, connects via websocket, and does a second render. This time the socket sticks around because you’ve got a persistent connection. Notably though on this run, there is no @conn. In fact it’s a totally separate request, that could even happen to a totally different server from the GET request.

In the GET request, the assigns can be copied into the socket, because the socket is just basically exists to help you avoid writing totally different code for the static render. BUT on the second request, there’s no @conn for the values to be copied from at all. This is why the socket |> assign_new function takes an anonymous function arg. On the GET request assign_new will just use the assign from the @conn. But on the second live request, how can it get its value? It runs the anonymous function.

16
Post #2
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

This is basically correct. What I did in my app is create a %Context{} struct which holds things like the current user. Then I setup this context for both plug and in my live view:

In my plug:

    case Common.Sensetra.lookup_context(conn.host, org_id, token) do
      {:error, :no_grant} ->
        conn
        |> redirect(to: "/")
        |> halt

      {:ok, ctx} ->
        conn
        |> assign(:context, ctx)
        |> assign(:host, conn.host)
        |> merge_assigns(assigns_from_context(ctx))

      {:error, %{"errors" => _}} ->
        conn
        |> put_session(:token, nil)
        |> redirect(to: "/")
        |> halt()
    end

In my live view:

  # elsewhere
  import CommonWeb.Socket
  # then
  def mount(params, session, socket) do
    socket = init_assigns(params, session, socket)
defmodule CommonWeb.Socket do
  import Phoenix.LiveView

  @doc """
  This initializes the socket assigns
  """
  def init_assigns(params, session, %Phoenix.LiveView.Socket{} = socket) do
    %{
      "token" => token
    } = session

    socket
    |> assign_new(:token, fn -> token end)
    |> assign_new(:host, fn ->
      get_connect_params(socket)["host"] || raise "pass in the host!"
    end)
    |> setup_context(session, params)
  end

  defp setup_context(socket, _session, params) do
    socket =
      socket
      |> assign_new(:context, fn ->
        {:ok, ctx} =
          Common.Sensetra.lookup_context(
            socket.assigns.host,
            params["organization_id"],
            socket.assigns.token
          )

        ctx
      end)

    socket
    |> assign(CommonWeb.Plug.Application.assigns_from_context(socket.assigns.context))
  end
end

I use assign_new because I also call Common.Sensetra.lookup_context() inside of a plug. That plug will do things like redirect you to login if there is no current user. Since I look it up in the conn, I use assign_new so that in the socket part of the GET request it isn’t called twice.

You can mostly ignore the whole "host" thing I pass in. Our application does subdomain based theming so it’s important for us.

12
Post #4
LostKobrakai

LostKobrakai

If you’re in the static render and you do assign_new(socket, :user, fn -> fetch_user() end) then phoenix will look at conn.assigns.user first and copy that value before falling back to executing the anonymous function.

Where Next?

Popular in Discussions Top

mikl
I wanted to capitalize a string, and tried using String.capitalize(). That generally works well, until you try to capitalize a word like...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
nunobernardes99
Hi there Elixir friends :vulcan_salute: In a recent task I was on, I needed to check in two dates which of them is the maximum and which...
New
AlexMcConnell
The reason that Rails is as popular as it is is because it’s very easy for relatively inexperienced developers to get a lot of work done....
588 19675 166
New
mbenatti
Following https://github.com/tbrand/which_is_the_fastest |> https://raw.githubusercontent.com/tbrand/which_is_the_fastest/master/imgs...
New
jer
I’ve been using umbrellas for a while, and generally started off (on greenfield projects at least) by isolating subapps based on clearly ...
New
hazardfn
I suppose this question is effectively hackney vs. ibrowse but we are at a point in our project where we have to make a choice between th...
New
acrolink
How does the two languages compare when it comes to server side application development? Any experiences or ideas? Thank you.
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

Other popular topics Top

ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
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
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
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
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
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
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
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