ream88

ream88

Handling events in Phoenix LiveComponents

Hello,

I’m currently struggling while programming the following reusable auto-complete component:

defmodule AppWeb.AutoCompleteField do
  use AppWeb, :component

  defmacro __using__(opts \\ []) do
    fun = Keyword.fetch!(opts, :search_function)

    quote do
      @impl true
      def handle_event("search", %{"_target" => [name]} = params, socket) do
        %{^name => value} = params
        %{id: id} = socket.assigns
        pid = self()

        spawn(fn →
          items = unquote(fun).(Map.fetch!(params, name))
          send_update(pid, __MODULE__, id: id, items: items)
        end)

        {:noreply, socket}
      end

      @impl true
      def handle_event("select", params, socket) do
        IO.inspect(params, label: "select")

        # TODO: send_update

        {:noreply, assign(socket, items: [])}
      end

      @impl true
      def handle_event("select", %{"index" => index}, socket) do
        index = String.to_integer(index)
        value = Enum.at(socket.assigns.items, index)

        {:noreply, assign(socket, items: [], value: value)}
      end
    end
  end

  attr :items, :list, default: []
  attr :"list-class", :string, default: ""
  attr :"item-class", :string, default: ""
  attr :"container-class", :string, default: ""
  attr :rest, :global

  def autocomplete_field(assigns) do
    ~H"""
    <div class={Map.get(assigns, :"container-class")}>
      <input
        role="combobox"
        type="text"
        {@rest}
        phx-change="search"
        phx-debounce="500"
        aria-controls="options"
        aria-expanded="false"
      />

      <%= if @items != [] do %>
        <ul role="listbox" class={Map.get(assigns, :"list-class")}>
          <%= for {suggestion, index} <- Enum.with_index(@items) do %>
            <li
              role="option"
              class={Map.get(assigns, :"item-class")}
              phx-click="select"
              phx-value-index={index}
            >
              <%= render_slot(@inner_block, suggestion) %>
            </li>
          <% end %>
        </ul>
      <% end %>
    </div>
    """
  end
end

It mostly works, the only problem is this that the first event, the debounced search is properly sent to the parent live view like this:

[debug] HANDLE EVENT
  Component: AppWeb.LocationLive.FormComponent
  View: AppWeb.LocationLive.Index
  Event: "search"
  Parameters: %{"_target" => ["name"], "name" => "a"}

But the following select event is sent incorrectly, hence the missing Component debug statement:

[debug] HANDLE EVENT
  View: AppWeb.LocationLive.Index
  Event: "select"
  Parameters: %{"index" => "0", "value" => 0}

Any ideas what I’m doing wrong? Or understand incorrectly?

Marked As Solved

ream88

ream88

Thanks a lot @codeanpeace and @trisolaran, solved it by providing an explicit phx-target attribute and forwarding it to all elements:

defmodule AppWeb.AutoCompleteField do
  use AppWeb, :component

  defmacro __using__(opts \\ []) do
    fun = Keyword.fetch!(opts, :search_function)

    quote do
      @impl true
      def handle_event("search", %{"_target" => [name]} = params, socket) do
        %{^name => value} = params
        %{id: id} = socket.assigns
        pid = self()

        spawn(fn ->
          items = unquote(fun).(Map.fetch!(params, name))
          send_update(pid, __MODULE__, id: id, items: items)
        end)

        {:noreply, socket}
      end

      @impl true
      def handle_event("select", params, socket) do
        IO.inspect(params, label: "select")
        # TODO: send_update

        {:noreply, assign(socket, items: [])}
      end

      @impl true
      def handle_event("select", %{"index" => index}, socket) do
        index = String.to_integer(index)
        value = Enum.at(socket.assigns.items, index)

        {:noreply, assign(socket, items: [], value: value)}
      end
    end
  end

  attr :items, :list, default: []
  attr :"phx-target", :any, required: true
  attr :"list-class", :string, default: ""
  attr :"item-class", :string, default: ""
  attr :"container-class", :string, default: ""
  attr :rest, :global

  def autocomplete_field(assigns) do
    ~H"""
    <div class={Map.get(assigns, :"container-class")}>
      <input
        role="combobox"
        type="text"
        {@rest}
        phx-change="search"
        phx-debounce="500"
        phx-target={Map.get(assigns, :"phx-target")}
        aria-controls="options"
        aria-expanded="false"
      />

      <%= if @items != [] do %>
        <ul role="listbox" class={Map.get(assigns, :"list-class")}>
          <%= for {suggestion, index} <- Enum.with_index(@items) do %>
            <li
              role="option"
              class={Map.get(assigns, :"item-class")}
              phx-click="select"
              phx-value-index={index}
              phx-target={Map.get(assigns, :"phx-target")}
            >
              <%= render_slot(@inner_block, suggestion) %>
            </li>
          <% end %>
        </ul>
      <% end %>
    </div>
    """
  end
end

Also Liked

codeanpeace

codeanpeace

Off the top of my head, I’d try setting phx-target within the <li> as described in the Targeting Component Events docs. You’ll probably need to pass in the parent LiveComponent’s @myself assign. My guess is that the <input> is working either because phx-target is set by the <form> it’s nested under or passed in via @rest.

trisolaran

trisolaran

You need to set phx-target otherwise the phx-click event will be sent to your live view.

Your function component needs to receive the target via assign and set it for its phx-click event.

Basically what @codeanpeace said :slight_smile:

Where Next?

Popular in Questions Top

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
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 record...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
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
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement