Preventing double clicks in Blazor components

October 7, 2024 · 2 minute read · Tags: aspnet | blazor

I’ve built a number of online stores over the years and one thing remains true…

Customers get pretty annoyed if you charge them twice for the same thing.

So how can you avoid such calamity?

Well you probably want to architect your backend to reduce the chances of an operation being called twice.

For example you might use a session id and block an order from being created/placed if another one has already been created for that session id.

But what about at the UI level?

The risk there is that the user clicks the same button twice, either through impatience or by accident.

In a Blazor app you can use a little bit of UI logic to disable a button once the user has clicked it.

The typical pattern is to toggle a flag when the user clicks the button, then toggle that flag back again after the operation completes.

Here’s a simple example.

@page "/buttonTest"
@rendermode InteractiveServer

<button @onclick="HandleClick" 
	disabled="@_isLoading" 
	class="@(_isLoading ? "loading" : "")"> 
  @ButtonText 
</button>
@code {
    private bool _isLoading = false;
    private string ButtonText => 
	_isLoading ? "Processing..." : "Click me";

    private async Task HandleClick()
    {
        _isLoading = true;

        await Task.Delay(3000); // Simulating a long-running operation

        _isLoading = false;
    }
}

As soon as the button is clicked, we toggle the _isLoading flag to true.

A little bit of conditional logic then sets the button to disabled (and, optionally, toggles a class on the button called loading).

Once the operation completes, we set the _isLoading flag back to false.

Simple, but effective.

Join the Practical ASP.NET Newsletter

Ship better Blazor apps, faster. One practical tip every Tuesday.

I respect your email privacy. Unsubscribe with one click.

    Next up

    Finally! Improved Blazor Server reconnection UX
    .NET 9 changes how your Blazor Server app behaves when server connection is lost
    .NET 9 improves JavaScript module importing for Blazor
    .NET 9 ensures your users always get the latest version of your JS modules
    How to use .NET 9 to ensure users always get the latest version of your stylesheets
    .NET 9 changes how static files are served, and it solves a long-standing problem