Each Blazor component has a method OnInitializedAsync() which can be overriden.
It seems to be a good place for any calls to fetch data which should be used during component render, like:
protected override async Task OnInitializedAsync()
{
var dataForRendering = await SomeHttpClient.RetrieveSomeData();
}
However, there is a known behavior in Blazor components where the OnInitializedAsync() method is fired twice. There is a description on how to handle it, in the Stackoverflow discussion.
The recommendation there was to check on the ComponentContext.IsConnected state which allows to fire required operations only once.
However, an update from September, 4th tells that we should
Remove any usage of
IComponentContextand move any logic that should not run during prerendering intoOnAfterRenderorOnAfterRenderAsync.
Using OnAfterRenderAsync instead is not an option here as well. Yes, it is being fired only once, but by the time it is fired, the component is already rendered and it is late to retrieve any data which should be used for rendering.
So the question is:
- How to avoid double-loading of data during 'OnInitializedAsync()' execution now? Twice the calls to the data server is not a good performance example.
- Is it a good idea to load data for a component render like that at all? Maybe there are better ways to pass data to a component?