How to prevent liveview double form submit

With just a simple form of

<form phx-submit="search">
  <button>
    Search
  </button>
</form>

and

def handle_event("search", %{"query" => q}, socket) do
    IO.puts("Searching")
    {:noreply, socket}
  end

I can see from the server logs that a double click on the form submit button produces two search events. I tried phx-throttle but it seems to only work for normal buttons and not form submit buttons.

phx-disable-with only changes the look of the button and does not disable submission.

Don’t think we can reliably depending on disabling button in accordance to a socket assigns attribute. The round trip will be slower than a double click.

Any ideas how i can do this?

Reading the docs, the button should be disabled:

On submission of a form bound with a phx-submit event:

  1. The form’s inputs are set to readonly
  2. Any submit button on the form is disabled
  3. The form receives the "phx-submit-loading" class

My suspicion is that for this to work, you need to add type="submit" on the button, have you tried that?

Update: Actually, I cannot reproduce the behavior from your example as it is, the button is always disabled until the response arrives. (Phoenix 1.7.2 with LV 0.18.18). Are you returning immediately in handle_event("search", ...) and pushing the search results at a later time, per chance? Otherwise I can’t really understand the behavior you’re seeing without more context.

Ah also: If your example is indeed all there is to it at the moment, then it’s very likely the case that the roundtrip is just that quick locally, meaning the button is already re-enabled when you’re hitting the mouse the second time when double-clicking. Try adding Process.sleep(3000) in handle_event to verify.

1 Like

Use the form component rather than a bare <form> element?

You are right. Its because of this. Thanks for enlightening me :pray:

I saw this in Form bindings — Phoenix LiveView v0.20.2 and was wondering why its not happening

On submission of a form bound with a phx-submit event:

  1. The form’s inputs are set to readonly
  2. Any submit button on the form is disabled
  3. The form receives the "phx-submit-loading" class

On completion of server processing of the phx-submit event:

  1. The submitted form is reactivated and loses the "phx-submit-loading" class
  2. The last input with focus is restored (unless another input has received focus)
  3. Updates are patched to the DOM as usual
1 Like