aNerdInTheHand

aNerdInTheHand

Context

I’m having some issues with getting a LiveView hook to fire when I assign things to the socket first. I have the following event handler in my live file (setup_live.ex):

def handle_event("save_personal_details", params, socket) do
  game_state = "setup_skills"
  socket = socket
  |> assign(:player, to_form(params))
  |> assign(:skills, to_form(@skills))
  |> assign(:game_state, game_state)
  |> push_event(
    "submit_player_personal_details",
    %{player: params, game_state: game_state}
  )

  {:noreply, socket}
end

In this case both params and @skills are just maps and will render correctly in a form (I mention this as I thought something may be going wrong with to_form but this doesn’t seem to be the case).

In a component I have a form with phx-hook="SetupPersonalDetails" and phx-submit="save_personal_details". So far so good, this event handler is called when I submit the form.

I then have a SetupPersonalDetails hook that looks like this:

export const SetupPersonalDetails = {
  mounted() {
    this.pushEvent("restore", {
      player: JSON.parse(localStorage.getItem("player")),
      game_state: localStorage.getItem("game_state") || "setup_personal_details"
    })

    this.handleEvent("submit_player_personal_details", playerPersonalDetails => {
      console.log('Updating player personal details...')
      localStorage.setItem("player", JSON.stringify(playerPersonalDetails.player))
      localStorage.setItem("game_state", playerPersonalDetails.game_state)
      console.log('Player name submitted')
    })
  }
}

The Problem

My hook never handles the submit_player_personal_details that’s emitted - unless I remove the assigns from my event handler. If I change my event handler in my live file to:

def handle_event("save_personal_details", params, socket) do
  game_state = "setup_skills"
  socket = socket
  |> push_event(
    "submit_player_personal_details",
    %{player: params, game_state: game_state}
  )

  {:noreply, socket}
end

in other words, remove the pipes into assigns, the JavaScript Hook runs and writes to localStorage correctly. What am I doing wrong here? I’m a bit of a Phoenix/Elixir novice, any help appreciated!

Showing Posts 1 to 7

cmo

cmo

Can we see the relevant part of the template?

aNerdInTheHand

aNerdInTheHand OP

Sure, sorry that was an oversight on my part:

defp about_you(assigns) do
  ~H"""
  <div class="p-2 m-2 w-1/2">
    <h2 class="text-xl sm:text-2xl font-bold text-center mb-4">About you...</h2>
    <.simple_form
      id="iptab-player-name"
      for={@player}
      phx-hook="SetupPersonalDetails"
      phx-submit="save_personal_details"
    >
      <.input type="text" field={@player[:first_name]} label="First name" />
      <.input type="text" field={@player[:last_name]} label="Last name" />
      <.input type="select" field={@player[:pronouns]} label="Preferred pronouns" options={[{"He/Him", "m"}, {"She/Her", "f"}, {"They/Them", "n"}]} />
      <.button type="submit">Next - Choose Your Skills</.button>
    </.simple_form>
  </div>
  """
end
ken-kost

ken-kost

What happens if you assign after?

def handle_event("save_personal_details", params, socket) do
  {:noreply, socket
  |> push_event("submit_player_personal_details", {player: params, game_state: "setup_skills"} )
  |> assign(player: to_form(params), skills: to_form(@skills),  game_state: "setup_skills")}
end

aNerdInTheHand

aNerdInTheHand OP

No difference I’m afraid, the JS listener still never runs

codeanpeace

codeanpeace

Hmm, just a guess but could there be a race condition?

Instead of pushing that data from the server to the client via the mounted callback in client side hook, try pulling that data to the client from the server in that client side hook after setting up the client side event handler. You could also piggyback of the "restore" event and send that data then. This would ensure the client side hook is ready to receive the pushed event.

cmo

cmo

Could try the hook on the parent div too.

aNerdInTheHand

aNerdInTheHand OP

Putting the hook on the containing div solved the issue. As @codeanpeace says I suspect it was a race condition, as I’m also using the restore event to assign data from local storage. I haven’t had much time to properly investigate it but seems that was the cause, thanks all!

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews