How to detect Pre-Rendering of a Component #53563
-
What is the team's recommended way to get the render state of a component? I currently use a service like this: public interface IBlazrRenderStateService
{
public Guid ServiceUid { get; }
public BlazrRenderState RenderState { get; }
public bool IsPreRender => this.RenderState == BlazrRenderState.PreRender;
}
public enum BlazrRenderState
{
None,
PreRender,
SSR,
CSR
} And the Server implementation: public class ServerRenderStateService : IBlazrRenderStateService
{
private IHttpContextAccessor _httpContextAccessor;
public Guid ServiceUid { get; } = Guid.NewGuid();
public BlazrRenderState RenderState =>
!(_httpContextAccessor.HttpContext is not null && _httpContextAccessor.HttpContext.Response.HasStarted)
? BlazrRenderState.PreRender
: BlazrRenderState.SSR;
public ServerRenderStateService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
} Which uses the Other programmers imply that I'm wrong in using it by quoting: "Microsoft does not recommend the use of
I understand why: users may/will grab, persist and then try and use the Your documentation describes it as the method of last resort, which I think is the case with Render State - https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-8.0#access-httpcontext-from-custom-components. The code is purely doing a proof of life and using that information to predict the state. But, you may have a better method? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Is AfterRender(bool firstRendered) to your liking |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
[CascadingParameter] HttpContext HttpContext {get; set; }
on your component. If you are prerendering it will be populated, in any other case it will be null.