aNerdInTheHand

aNerdInTheHand

Issues with assigns and push_events

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!

First 7 of 7 Posts! Switch mode

cmo

cmo

Can we see the relevant part of the template?

aNerdInTheHand

aNerdInTheHand

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

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

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!

Where Next?

Trending in Questions Top

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
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
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
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
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
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
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
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement