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

yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
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
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
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
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 Postg...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
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

We're in Beta

About us Mission Statement