Mackan
Mackan

Reputation: 6271

Blazor, return from/halt rendering if loading

We have similar code as below in all our Blazor pages, to simply halt the rendering until loading is done. It seems to work ok, but the site has not had that much testing yet.

I am a bit worried that this, meaning the return; in the middle of the page, will/could mess up blazors flow in one way or another, lead to memory leaks or whatever.

Every example I see uses if/else instead, but if the below example is valid it's much preferred to reduce nesting and complexity of the page.

So, is this method ok to use, or will it cause us problems down the line?

A simplified example:

@usings/injects here
    
@if (IsLoading)
{
    @:Loading content..
    return;
}
    
<p>This will not be rendered until page is initialized and Model populated</p> 
<p>@Foo.Bar</p>
    
@code {
    public bool IsLoading { get; set; } = true;
    public FooModel Foo { get; set;}
    
    protected override async Task OnInitializedAsync()
    {
        try
        {
            Foo = await GetFooFromRepo();
        }
        catch (Exception ex)
        {
            Toaster.Add("Something went wrong when loading foo.", 
                 MatToastType.Danger, "Error");
        }
        finally
        {
            IsLoading = false;
        }
    }
}

Upvotes: 4

Views: 1019

Answers (2)

StPaulis
StPaulis

Reputation: 2916

I would not use this approach,

The way I recommend to do this it would be with an @if-else statement, like the follow:

@if (IsLoading)
{
    @:Loading content..
}
else 
{  
  <p>This will not be rendered until page is initialized and Model populated</p> 
  <p>@Foo.Bar</p>
}
    

Upvotes: 5

Henk Holterman
Henk Holterman

Reputation: 273179

This is a matter of taste or style.

There is nothing intrinsically wrong with it, you are just returning form a method.

In this post it is likened to spaghetti code but that depends. The way you write this the return is very clear and hard to overlook. And the alternative else { } has its own reading costs.

Upvotes: 2

Related Questions