I'm stuck as how to optimize rendering of a typical data-driven Blazor component. Consider the following simplified component (partial):
public partial class FooComponent: ComponentBase
{
[Inject]
protected IBarService BarService { get; set; }
[Parameter]
public string OptionalParameter1 { get; set; }
[Parameter]
public string OptionalParameter2 { get; set; };
protected IEnumerable<BarItem> Items { get; set; }
protected override Task OnParametersSetAsync()
{
this.Items = await this.BarService.GetItemsAsync(this.OptionalParameter1, this.OptionalParameter2);
}
}
The component has two optional parameters. They could typically be some filtering values for the service call. The component has no way of knowing whether any of these parameters will be set by the parent component (since they are optional). Whenever a parameter is set, the component retrieves a list of BarItem items via an (expensive) async service call. The component markup then renders the Items list in some way.
The problem is that OnParametersSetAsync is called everytime a parameter is set, causing the component to re-render and do another service call. I can partially optimize this by checking if the parameter values have changed, but there will still be multiple service calls.
- If both parameters are never set, the service call happens once (good).
- If one parameter is set, the service call happens twice (first time with wrong parameter values).
- If both parameters are set, the service call happens 3 times (first 2 times with wrong parameter values).
In a real-world component with more properties this can quickly result in many unwanted service calls. If OnParametersSetAsync would be called once for all parameters, this would not be a problem (I understand that Blazor does not work this way).
Is there something I can do to make sure service calls only happen once with the correct parameter values? This seems to me like a very common scenario in data-driven components, and it would be a real shortcoming for Blazor if this is not possible to implement (efficiently).
OnAfterRenderAsync- agua from mars