Prevent double clicks in LiveView

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’s innerText 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>
1 Like

That also sounds like phx-debounce, phx-throttle, from the same doc page :slight_smile:

1 Like

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.

2 Likes

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.

2 Likes