Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option update callback #62

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

aakashjhawar
Copy link

@aakashjhawar aakashjhawar commented Mar 25, 2024

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

@maxmarcon
Copy link
Owner

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

@aakashjhawar
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants