IgniteUI / igniteui-xplat-examples

MIT License
2 stars 1 forks source link

[Blazor] simplify async/await syntax to improve readability #162

Open jsakamotoIGJP opened 1 year ago

jsakamotoIGJP commented 1 year ago

We can see the example code for the IgbAvatar component that handles asynchronous operations with the ContinueWith method chain, as below.

https://www.infragistics.com/products/ignite-ui-blazor/blazor/components/layouts/avatar

protected override void OnAfterRender(bool firstRender)
{
    base.OnAfterRender(firstRender);
    if (this.ChildIcon != null && firstRender)
    {
        this.ChildIcon.EnsureReady().ContinueWith(new Action<Task>((e) =>
        {
            this.ChildIcon.RegisterIcon("home", "https://....svg", "material");
        }));
    }
}

However, usual C# developers will use the async/await syntax in these cases, as below.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (this.ChildIcon != null && firstRender)
    {
        await this.ChildIcon.EnsureReady();
        this.ChildIcon.RegisterIcon("home", "https://....svg", "material");
    }
}

Using the async/await syntax is simpler and more readable than method chain syntax. Moreover, the current example code above doesn't handle any exceptions. If we use the async/await syntax, the exception will be thrown appropriately whenever it happens.

All of the example codes on the Ignite UI for Blazor documents should use the async/await syntax as long as there is no particular reason for avoiding it.


P.S. You don't need to call a base method in the lifecycle methods in Razor components.

protected override void OnAfterRender(bool firstRender)
{
    base.OnAfterRender(firstRender); // 👈 You don't have to do this.

There is no example code that the base methods are called in Blazor lifecycle methods on the Microsoft official documentation site. https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-7.0

HUSSAR-mtrela commented 1 year ago

@mddifilippo89 can you fix the first part of this issue? I have already fixed second part of issue with not need base.OnAfterRender() functions calls