Can I use phx-mounted to send me form params BEFORE user has updated anything?

I have a LiveView for an Event that uses multiple components to collect parameters for creating and updating an Event.

  • Each component has a form that collects a subset of the Event’s params.
  • Each component “sends” its params back up to the parent LiveView
  • the Parent Liveview merges all of the params together and then validates and processes them

The issue is that a component won’t send params until a user makes a change which triggers an event. But I need ALL of the components to send their initial state of params BEFORE the user makes any changes.

Yes … I could parse these params out of the %Event{} that is passed around to each component, but I feel like there must be a way to trigger the forms to send an event (where I could grab the params) when the form is first mounted.

In essence … I need to do a roll-call with all of my components and make them tell me the status of their params before ANY changes are made.

I saw phx-mounted and thought that maybe I could use that, but i don’t know JavaScript.

Is it possible to use phx-mounted to throw an event with all of the current params in a component’s form? If so, could someone send me the code that I would use? Here is the code from the hex docs:

<div id="flash" class="hidden" phx-mounted={ ...)}>
  Welcome back!

Instead of … I need something like JS.throw_an_event_that_will_give_me_the_params. :slight_smile:

You could probably use JS.push/2 inside phx-mounted to push an event with the initial state to your LiveView.

1 Like

Thank you! I had never seen that module! I thought was JavaScript. I didn’t realize that is part of Phoenix.Liveview.JS. Super cool!

Sadly … this did not work. I tried every combination of phx-mounted (as a div, inside <.form>, inside the html tags) and everything failed. I was never able to get it to successfully push an event. I even tried it in the LiveView (instead of a component) and nothing happened. I tried to find more examples of how phx-mounted is used, but there is very little on it. So I’m abandoning this approach. Just posting this in case someone else tries to go down this path. If you get phx-mounted to work … I’d love to see your code!

Sorry my fault.
You need to use phx-connected instead of phx-mounted since the underlying websocket connection isn’t yet established on mount.

This minimal example works for me:

defmodule PhxWeb.MountedLive do
  use PhxWeb, :live_view

  def mount(_, socket) do
    {:ok, socket}

  def render(assigns) do
    <h1 phx-connected={JS.push("header_mounted", value: %{state: "Some state"})}>Hello, World!</h1>

  def handle_event("header_mounted", value, socket) do
    IO.inspect(value) # Prints %{"state" => "Some state"}
    {:noreply, socket}
1 Like

Thank you!!! I’ll give that a try!