How to get app.html.heex to use assigns properly with LiveView

Background

I have a Phoenix application, where all pages (expect the login page) have a menu at the top.
This menu will therefore only appear if the user has already logged in.

I am trying to replicate this behaviour, by incorporating said menu in the app.html.heex so I don’t have to repeat it constantly.

However, no matter what I do, the menu is never displayed.

Code

I am trying to change my app.html and verify if the user logged in using assigns[:user].

app.html.heex:

<header>

 <%= if assigns[:user] do %>
   <h1> Cool Menu here </h1>
 <% end %>

</header>

<main class="">
  <div class="mx-auto max-w-2xl">
    <.flash_group flash={@flash} />
    <%= @inner_content %>
  </div>
</main>

The login process is async, as shown here. Basically I send a login request to a Manager, and when it feels like replying back, I update the socket with assigns[:user] and redirect to a cool page.

user_login_live.ex:

defmodule WebInterface.MyAppLive do
  use WebInterface, :live_view

  @impl true
  def mount(_params, _session, socket), do: {:ok, socket}

  @impl true
  def handle_event("login", params, socket) do
    IO.puts("Seding async request")
    :ok = Manager.login(params)
    {:noreply, socket}
  end

  @impl true
  def handle_info({:login,  user, :done}, socket) do
    IO.puts("Authentication succeeded for user #{inspect(user)}")

    updated_socket =
      socket
      |> assign(:user, user)
      |> redirect(to: ~p"/cool_page")

    {:noreply, updated_socket}
  end

end

I would expect the cool page to have the <h1> menu, but that is not the case.

Questions

  • What am I doing wrong here?
  • Isn’t the assigns updated automatically?
  • Does app.html.heex work differently from other files?
1 Like