I'm using MudBlazor's MudTextField component to take in a string and I'm trying to run some validation on it asynchronously as I expect it to take a long time to validate. Other components in my app are disabled based off the results of the validation, so I use a flag to keep track of whether the input is valid. My general code setup is this:
<MudTextField Validation=ValidateValue />
@code{
private async Task<string?> ValidateValue(string newVal){
/* Do some prep */
string? ErrorMessage = await Task.Run(() => SomeLongValidation());
StateHasChanged() // Without this, the state doesn't update and the page doesn't see the updated flag
return ErrorMessage;
}
private string? SomeLongValidation(){
Thread.Sleep(2000);
return "Dummy Error Text";
}
}
If I run the validate value as a synchronous operation where I don't put the long validation as a task, I don't need the state has changed call and everything updates properly.
With some research, I've seemed to have found places that suggest when you await something, the StateHasChanged in the parent that would get called at the end of the operation gets called early, and thats why we have to call it ourselves, but I didn't see anything completely confirming that, and I found a few sources that almost disagreed. I believe it has something to do with MudBlazor specifically, but I'm not sure.