Arsenalist

Arsenalist

I have the following live session:

  scope "/live", AmplifyWeb do

    live_session :default,
      layout: {AmplifyWeb.Layouts, :admin},
      on_mount: AmplifyWeb.Live.TokenValidator do

      live "/mailing-lists/:mailing_list_id/import-subscribers", ImportSubscribers
      live "/events/performance", EventPerformance

    end

  end

I want to validate a token from the query string in TokenValidator.on_mount and store the user_id from it in session so that it is available to all LiveViews within the live_session.

However, when I set anything on socket or session in on_mount, it is not available in the LiveView. I understand that’s because they are different instances of socket which makes sense. But how do I go about reading an initial value from query string and keeping it around in session or somewhere else where it can persist across LiveViews in the same live_session (and persist it across refreshes)?

Showing Posts 1 to 10

jswanner

jswanner

What have you tried in the on_mount function, as assigns set there should be available in the LiveViews?

Arsenalist

Arsenalist OP

Hi,

Here is the on_mount method in TokenValidator:

  def on_mount(:default, %{"api_token" => api_token} = params, session, socket) do
    case validate(api_token) do
      {:ok, user_id} ->
        {:cont,
         assign(socket, :user_id, user_id)
         |> assign(:api_token, api_token)
         |> assign(:account_id, params["account_id"])}

      {:error, 401} ->
        {:halt, redirect(socket, to: "/login")}
    end
  end

The values I set appear fine in the first LiveView I load. Then I use <.link navigation="/events/performance".../> and expect the information to be there in the second LiveView but it’s empty (and it’s also empty in the on_mount right before the second LiveView is loaded)

Bascially, I just want this info to be available in all LiveViews for that live_session.

sodapopcan

sodapopcan

Check on_mount.

Sorry that was a massive mis-read :upside_down_face:

You are grabbing api_token from params in a function head match. It looks like your <.link> doesn’t include the API token in the query string—ie, <.link navigate="/events/performance?api_token=#{@api_token}" ...>, so the on_mount isn’t going to match.

Arsenalist

Arsenalist OP

I only expect the api_token to be there in params the first time any of the LiveViews in the live_session load. After that I want to store it in “session” or somewhere else, so that other LiveViews can access it (without me explicitly passing it on every single <.link> as a query parameter). Is what I’m trying to do even possible, or do I just have to store it in database?

sodapopcan

sodapopcan

Honestly it’s been a while since I’ve had to deal with an API so not sure of best practices off the top of my head but yes, you’re going to need to store it somewhere else. The main point is that your callback is matching on params in the function head so it won’t run if it can’t match that. You’d have to have multiple heads or do something like:

  def on_mount(:default, params, session, socket) do
    api_token =
      cond do
        params["api_token"] -> params["api_token"]
        session["api_token"] -> session["api_token"]
        _ -> raise "oh no!"
      end
    end
  end

I’m not recommending this exact code, but you need some sort of conditional logic to get the token from params or the session/other data-store and not match in the function head (or have multiple function heads).

Arsenalist

Arsenalist OP

yes, I have all that code which does multiple matching. but the problem is that the data simply isn’t available anywhere in a LiveView (in on_mount, handle_params) after you click the <.link>. I suppose I will use the session id as a key to store info on the server side and load it from there. I just though LiveView would take care of this use case which is fairly common I would imagine.

sodapopcan

sodapopcan

I can’t explain then as that should definitely work! Can you show your full code?

Arsenalist

Arsenalist OP

router.ex

  scope "/live", AmplifyWeb do
    pipe_through [:browser]

    live_session :default,
      layout: {AmplifyWeb.Layouts, :admin},
      on_mount: AmplifyWeb.Live.TokenValidator do
      live "/mailing-lists/:mailing_list_id/import-subscribers", ImportSubscribers
      live "/events/performance", EventPerformance
    end
  end

TokenValidator:

   # gets called correctly and info is available in the first LiveView that is rendered
  def on_mount(:default, %{"api_token" => api_token} = params, session, socket) do
    case validate(api_token) do
      {:ok, user_id} ->
        {:cont,
         assign(socket, :user_id, user_id)
         |> assign(:api_token, api_token)
         |> assign(:account_id, params["account_id"])}



      {:error, 401} ->
        {:halt, redirect(socket, to: "/login")}
    end

  # if no query parameters are supplied, we don't care and just return socket
  # since I'm hoping (praying) that the stuff I stored earlier is still available in some assigns
  def on_mount(:default, _params, _session, socket) do
     {:cont, socket}
  end

Everything is good so far but now let’s click Link to render another LiveView:

    <.link
      navigate={"/live/events/performance"}
    >Event Performance
    </.link>

LiveView:

defmodule AmplifyWeb.EventPerformance do
  use AmplifyWeb, :live_view
  import AmplifyWeb.PageName

  @impl Phoenix.LiveView
  def mount(_params, session, socket) do
    # this contains nothing
    IO.inspect(session, label: "Session in EventPerformance") 
    IO.inspect(socket, label: "Socket in EventPerformance")
    ....
  end
end
sodapopcan

sodapopcan

Ah yes, you have to pull it out of the session in the catch-all clause. live_session only maintains the same process, but you still need to recreate the state as it starts the mounting process all over again. To avoid mounts you would <.link patch=""> although I actually totally forget if patching between LVs works of not (think it just gets silently converted to a navigate). This keeps things sane and easy to reason about as a mount is always a mount, ie, always starting from a clean slate.

Arsenalist

Arsenalist OP

That’s what I thought too, but in the catch-all case, there’s nothing in the socket.assigns (the stuff set during the first on_mount is gone) so I’m left with nothing to pull out.

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews