Search code examples
validationasynchronousblazorblazor-client-sidematblazor

Disabling button from async function in Blazor


I have following EditForm model on my page:

<EditForm Model="@projectParameters" OnValidSubmit="@SubmitProject">
       <MatButton Raised="true" Type="submit" Disabled="@saveButtonDisabled">@saveButtonName</MatButton>
</EditForm>

Then the following functions:

private async Task SubmitProject()
    {
        DisableSave();

        if (pageType == "Create")
        {
            await CreateProject();
        }
        else if (pageType == "Create")
        {
           await EditProject();
        }
    }

and

void DisableSave()
    {
        saveButtonDisabled = true;
        saveButtonName = "Saving...";
        StateHasChanged();
    }

SubmitProject & DisableSave are properly called, but the saveButtonName & disabled never actually show as completed when CreateProject is working. What am I missing?


Solution

  • Flush changes with await Task.Delay(1);:

    private async Task SubmitProject()
    {
        await DisableSave();
        ...
    

    Then

    async Task DisableSave()
    {
        saveButtonDisabled = true;
        saveButtonName = "Saving...";
        await Task.Delay(1); //flush changes
        StateHasChanged(); // not needed
    }