yirk
yirk

Reputation: 63

Call method on parameter change

I have a component than gets data to display from WebAPI using parameter. Parameter comes from parent component and I need to refresh data when parameter's value changes.

@if (somedata != null)
{
    <span>@somedata.FirstOrDefault()?.SomeValue</span>
}
@code {
    [Parameter]
    public int SelectedLine
    {
        get => selectedLine;
        set
        {
            if (selectedLine != value)
            {
                selectedLine = value;
                UpdateAsync();
            }
        }
    }
    private int selectedLine;
    private List<SomeData> somedata;

    protected override async Task OnInitializedAsync()
    {
        await UpdateAsync();
    }
    private async Task UpdateAsync()
    {
        somedata = await SomeRepo.GetAsync(SelectedLine);
    }
}

Code works well but I got warning ("Because this call is not awaited, execution of the current method continues before the call is completed") and I think this is not a very elegant decision. How can it be done right?

Upvotes: 4

Views: 4268

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273179

You can use OnParametersSetAsync() to properly await getting your data.

And then the property doesn't need a setter anymore.

[Parameter]
public int SelectedLine { get; set; }

protected override async Task OnParametersSetAsync()
{
    await UpdateAsync();        
}

Upvotes: 7

Related Questions