Tom
Tom

Reputation: 836

Blazor Component Lifecycle - How do you do something async in the component after parameters are set but before they bind

I have a Dialog Component that pops up to edit a row of a grid.

When you click the row, I set a selectedItem variable which is bound to a parameter of my dialog component and make the dialog visible.

<MyDialog @bind-MyObject="selectedItem" @bind-Visible="dialogVisible" />

The problem is the MyDialog component needs to get a property from selectedItem then make an async call to an API and load some data before the selectedItem binds to all the fields in the dialog.

If I make my API call in OnParametersSetAsync(), it is too late, the selectedItem is already bound.

If I try to use SetParametersAsync(ParameterView parameters), you get an error if you try to do something async before calling the base implementation which binds the parameter.

This seems like a fairly normal scenario, is there another approach here?

Upvotes: 1

Views: 498

Answers (1)

Neil W
Neil W

Reputation: 9112

Conditionally show the bound elements:

@if (_ready)
{
    <label>@MyObject.SomeProperty</label>
}

@code {
    [Parameter] public MyClass MyObject { get; set; }

    // Do not create elements bound to parameter until I say
    bool _ready = false;   

    protected override async Task OnParametersSetAsync()
    {
        await MyApi.GetSomeMoreData();
        // Done what I need to do, you can render the bound elements now
        _ready = true;   
    }
}

Upvotes: 2

Related Questions