Reputation: 1
I'm working on a Blazor Server application and I've noticed an issue where the OnInitialized method is being hit twice - once during prerendering and again after the connection has been established in the browser. This is causing a static HTML razor component that has an animation done in CSS to animate twice.
Here's a simplified example of my component:
@page "/example"
<h3>@title</h3>
@code {
private string title;
protected override void OnInitialized()
{
title = "Page is initialized";
Console.WriteLine("OnInitialized is called");
base.OnInitialized();
}
}
In this example, "OnInitialized is called" is printed twice in the console, and the title "Page is initialized" is set twice. This is a simplified example, but in my actual application, I have a CSS animation that is triggered during initialization, and this animation is also happening twice.
I understand that Blazor Server operates in a way that it initializes components during prerendering and again after establishing a connection. But is there a way to prevent this double initialization, or at least a way to detect whether the initialization is happening during prerendering or after connection so I can control the animation accordingly?
Any help would be greatly appreciated. Thank you.
Upvotes: 0
Views: 850
Reputation: 176
You can modify the render-mode from ServerPrerendered to Server in _Host.cshtml
:
<component type="typeof(App)" render-mode="Server" />
More info here: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-6.0#stateful-reconnection-after-prerendering
Upvotes: 2