I'm making a Blazor Server Side project and I wanted to make a button that desactivate after a click, but without using the disabled
attribute of <button>
. The code is pretty simple :
@functions {
LogInForm logInForm = new LogInForm();
bool IsDisabled;
SignInResult result;
protected override void OnInitialized()
{
IsDisabled = false;
}
async Task TryLogIn()
{
IsDisabled = true;
StateHasChanged();
result = await _LogInService.TryLogIn(logInForm);
Console.WriteLine("Logging status : " + (result.Succeeded ? "Sucess" : "Failure"));
IsDisabled = false;
StateHasChanged();
}
}
For odd reasons, the first StateHasChanged
isn't triggering but the second does re-render the page. It can be quite easily testes by going in Debug mode and entering into the StateHasChanged()
method. On second time call it does stop on the HTML code after going into the method but not the first time.
Why so ?
NB : I'm not looking for any workaround using Task.Delay
or Task.Run(...)
only, as it exist a race condition between those threads and the UI refresh thread, and so it is not a reliable solution. I'm looking for answers on the StateHasChanged()
behaviour or a workaround by using events like PropertyChanged
or EventCallback
and putting the button as a child component.
Edit : After some testing, it seems that StateHasChanged()
only triggers the re-render of the component after an await
operation on a Task
. It can be easily tested by putting in commentary the result = await _LogInService.TryLogIn(logInForm);
line or changing IsDisabled = ...
to await new Task.Run(() => { IsDisabled = ...})
. I have some workaround now, but I still wonder why this is a feature. Shouldn't StateHasChanged()
re-render after any operations ? Or it consider that only async
operations (so mostly server-calls) can change something in the UI ?
Task.Delay(1)
workaround only, which, has said in the Nota Bene, isn't reliable due to race condition. Beside, I'm more asking an answer on howStateHasChanged()
works or how to do it by using events works more than having a workaround.TryLogIn()
isn't a fake async as it uses aSignInManager
to check and sign in the user.