Hi.
Wondering what is the best way to prevent double clicks in buttons/links in LiveView. In JS you’d typically disable a button as the first thing after it was clicked. Use a phx-hook, or is there a better solution?
Best regards,
Alf
Hi.
Wondering what is the best way to prevent double clicks in buttons/links in LiveView. In JS you’d typically disable a button as the first thing after it was clicked. Use a phx-hook, or is there a better solution?
Best regards,
Alf
That sounds like phx-disable-with:
To handle latent form submissions, any HTML tag can be annotated with
phx-disable-with
, which swaps the element’sinnerText
with the provided value during form submission. For example, the following code would change the “Save” button to “Saving…”, and restore it to “Save” on acknowledgment:<button type="submit" phx-disable-with="Saving...">Save</button>
That also sounds like phx-debounce, phx-throttle, from the same doc page
Thanks for the quick reply.
We are actually using phx-disable-with, however it does not actually prevent double clicks. Tested it by sleeping on the server, and there is nothing preventing me from clicking many times.
A phx-throttle solution will probably be good enough though. Although it would’ve been nice if phx-disable-with did the job, which seems like the “right” approach.
can you try:
<div class="phx-loading-hide">
<%= submit "Save" %>
</div>
<div class="phx-loading-show">
<%= submit "Saving...", disabled: true %>
</div>
per https://github.com/phoenixframework/phoenix_live_view/pull/633
Ran into this upgrading from an older LiveView install and this is the fix:
I can put that on my phx-click
buttons with the class phx-click-loading
and buttons are disabled as expected.
For future readers…
Tested phx-disable-with
in liveview 0.17.8 and it correctly prevents additional clicks while disabled (adds a disabled
attribute to the button
element).
Perhaps this was a bug in Apr 2020, which now seems to be resolved.