Skip to content

Blazor: OnInitializedAsync with prerendering #15266

@JDBarndt

Description

@JDBarndt

This was already mentioned in #13607, #14977, and #13448. OnInitializedAsync will fire twice, once during pre-rendering and once after the app bootstraps. This is apparently by design.

Is there any recommendation on how to avoid requesting the data for the page/component more than once?

An example of why this could be problematic is with the Blazor demo's weather forecast page:

FetchData.razor:

protected override async Task OnInitializedAsync()
{
	forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}

When loading into this page with prerendering, you'll see the initial grid loaded with weather data. Then, the app bootstraps and the component re-initializes a second time and sends an updated grid back to the client, replacing the initial grid with a new one. That's easily visible to the end-user because GetForecastAsync returns randomized data.

That particular data set is generated in-memory and has no meaningful performance impact, but if it instead was the result of a database, external API, or other call, you certainly wouldn't want to do that more than once. Obviously caching of some kind can and likely would be a solution, but I'm wondering if there is some other way within Blazor to avoid multiple requests.

I would almost expect that between prerendering and the app bootstrapping, the initial component state is "shared" so that it knows it doesn't have to regenerate, especially after reading https://docs.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.0#stateful-reconnection-after-prerendering:

The client reconnects to the server with the same state that was used to prerender the app. If the app's state is still in memory, the component state isn't rerendered after the SignalR connection is established.

Must be missing something here? Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocsThis issue tracks updating documentationarea-blazorIncludes: Blazor, Razor ComponentsenhancementThis issue represents an ask for new feature or an enhancement to an existing one

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions