maxmarcon / live_select

Dynamic (multi)selection field for LiveView
https://hex.pm/packages/live_select
Apache License 2.0
186 stars 35 forks source link

LiveView usage question #71

Closed guessthepw closed 5 months ago

guessthepw commented 5 months ago

I have a question about usage in a LiveView. Lets say I have a form with two inputs one text input and one live_select:

<.form for={@form} phx-change="change">
  <.input field={@form[:name]} type="text" /> 
  <.live_select field={@form[:class]} mode={:single} /> 
</.form>

I would initialize the form on mount and then we have two different handle_event handlers

def mount(params, session, socket) do
  form = 
    %{"name" => "", "class" => ""}
    |> Phoenix.Component.to_form()

  {:ok, assign(socket, :form, form}}
end

# This is for the text input
def handle_event("change", %{"_target" => ["name"]} = params, socket) do
  # Wrecks havoc on live selects but is best practice
  {:noreply, assign(socket, :form, Phoenix.Component.to_form(params)}}
end  

# This is for the live select
def handle_event("change", %{"_target" => ["class"]} = params, socket) do
  # Not sure what to do here, my options are
  # 1. Reassign form assigns like above 
  # 2. Send new value with send_update call
  # 3. Both of the above
  # 4. None of the above
 {:noreply, socket}
end  

I believe the current best practices for LiveView forms is to to take the params passed into the "change" event and pass them toPhoenix.Component.to_form and reassign the @form assign. This seems to wreck havoc on live_selects. (or I'm doing something else wrong)

I think sending an update with send_update and updating the @form assigns causes a race condition and ends up displaying the "value" instead of the "label" for selected options.

I'm not really sure how I'm supposed to handle this scenario, any guidance?

guessthepw commented 5 months ago

@maxmarcon

maxmarcon commented 5 months ago

I'm afraid "wreak havoc" is not an actionable error report. What happens? What exception do you get?

There's no special handling needed for live select inputs, unless you're dealing with something that needs to be JSON encoded/decoded

guessthepw commented 5 months ago

I apologize for the incomplete error report. That is completely on me.

The main issue I was having when I said "wreak havoc" was that the live select was displaying the "value" instead of the "label" when updating @form in assigns.

There's no special handling needed for live select inputs, unless you're dealing with something that needs to be JSON encoded/decoded

This makes me think its something to do with my setup. Today I will write up a complete error report / single file example and comment here regardless of I get it working as expected.

Thank you for getting back to me so fast.

guessthepw commented 5 months ago

This was an error on my end.

My apologies.