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!