Preventing double clicks in Blazor components
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.