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

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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
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
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New

We're in Beta

About us Mission Statement