live_select icon indicating copy to clipboard operation
live_select copied to clipboard

Option update callback

Open aakashjhawar opened this issue 1 year ago • 3 comments

Define a callback to send updated options to the LiveView or Component where LiveSelect component is initialized.

aakashjhawar avatar Mar 25 '24 11:03 aakashjhawar

Hi! What is the use-case for this change? When an option is selected/removed, a change event is triggered on the form, right?

maxmarcon avatar Mar 28 '24 06:03 maxmarcon

Hi, @maxmarcon!

Yes, when an option is selected / removed, an event is triggered to the form.

To get notified of any option selected / removed, we need pass on_option_update attribute and handle its update event in the form.

When initializing live_select from a LiveView, we can use:

<.live_select 
  field={@form[:city_search]} 
  on_option_update={fn option -> send(self, option) end}
/>

and to handle its event:

def handle_info(%{option_click: option}, socket) do
  ...
  {:noreply, socket}
end

def handle_info(%{option_remove: option}, socket) do
  ...
  {:noreply, socket}
end

If initializing it inside another component, one may write:

<.live_select
  field={@form[:city_search]}
  phx-target={@myself}
  on_option_update={fn option -> send_update(@myself, option) end}
 />

and to handle its event:

def update(%{option_click: option}, socket) do
  ...
  {:ok, socket}
end

def update(%{option_remove: option}, socket) do
   ...
  {:ok, socket}
end

This can be useful in cases when someone wants to do certain actions while the user is selecting options, or to track user activity.

aakashjhawar avatar Apr 03 '24 14:04 aakashjhawar

Hi sorry my comment wasn't clear: you're already getting a change event in the form when the user selects/deselects an option. I don't see the need for passing a callback to get the same information.

maxmarcon avatar Jun 11 '24 09:06 maxmarcon