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

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews