eddyraz

eddyraz

How to use hooks with data generated from the server

good Afternoon, I have a live_view component with a input hidden field “attached” to a phx-hook

1–in the template:

<form id="login_form" phx-submit="check_login_credentials">
<input type="hidden" id="login_token" phx-hook="input_login_token"/> 
.
.
.
</form>

2–in the server:
there’s a function handle_event/3 that processes the username and password and send it to an external Auth API in Django using djoser REST API. and receives a token.

def handle_event("check_login_credentials", params, socket) do
login_tkn="823703847509432870598743205987" #test dummy  data
if login_tkn do
  {:noreply, push_event(socket, "saveLoginToken", %{login_token : login_tkn}
.
.
.
    end 
end 

3—in the hooks file app.js theres a hook declared who manipulates the data sent from the server

let hooks = {}

hooks.saveLogintoken ={
mounted() {
    localStorage.clear()
    this.handleEvent("saveLoginToken", ({login_tkn}) =>  localStorage.setItem("login_token", login_tkn)
  },
};

When I put a console.log(something) in after the mounted() section it prints in the console, but any code put in this.handleEvent() section is not executed, If i take the other aproach and use
this.el.addEventListener("input", e => {....} it works but not handleEvent

could anybody explain why is not working, thanks in advanced.

Marked As Solved

mcrumm

mcrumm

Phoenix Core Team

The problem is in send_token_to_browser:

Note that push_event returns a modified socket struct- the event is not pushed to the client until you return from the LiveView callback. You are not receiving the event on the client because you are not returning the socket struct containing the event.

Also Liked

imkleats

imkleats

There’s one other typo that could be problematic if it’s not just erroneous transcription.

The event payload in the Elixir side has a key of login_token, but the object destructuring on the JS side’s handleEvent call is using the key login_tkn which would be undefined based on the payload coming across the socket.

Terbium-135

Terbium-135

If you are using push_event:

Phoenix Liveview adds the string phx: in front of the event name.
So "saveLoginToken" becomes "phx:saveLoginToken"

Have a look at

with the topic: Handling server-pushed events


let liveSocket = new LiveSocket(...)
window.addEventListener(`phx:highlight`, (e) => {
  let el = document.getElementById(e.detail.id)
  if(el) {
    // logic for highlighting
  }
})

Not sure if this is the reason for your problem

eddyraz

eddyraz

Thanks so much,

I put it this way, and it worked:

@impl true
  def handle_event("check_login_credentials", params, socket) do
    login_token = process_token_request(params["user_name"], params["password"], socket)

    send_token_to_browser(socket, params, login_token)
  end

  @impl true
  def send_token_to_browser(socket, params, login_token) do
    if login_token do
      socket = socket |> assign(:is_authenticated, true)
      {:noreply, push_event(socket, "save_login_token", %{payload: login_token})}
    else
      {:noreply, assign(socket, params: params)}
    end
  end

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
dotdotdotPaul
Okay, I’m having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I’m sure I’...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement