Why is OnInitializedAsync() called twice on a page reload #54579
Replies: 1 comment
-
I owe an apology to the Blazor team for my editorial comment above (leaving it up to own my mistake). They do have this answered in Persist prerendered state. The short answer is I'll add my own take to this too. Instead of using PersistentComponentState I'm going to try using a And again, apologies to the Blazor team for my editorial comment above and apologies to everyone here for wasting your time when this is answered. |
Beta Was this translation helpful? Give feedback.
-
Normally when a page is being created & rendered in Blazor version 8, RenderMode.InteractiveServer,
OnInitializedAsync()
is called once. But when I do a Reload on Chrome, it is called twice. And all child components in the page are called twice too.Why is it being called twice? And what can I do to avoid reading from the database to populate the page twice? And very importantly, in a way that will call from the database at least once for any situation?
Update: Ok, every time I think I finally understand the rendering mode, I realize I have it wrong again. (In my defense, I was told by someone I respect that InteractiveServer was changed to only call OnInitializedAsync() once. And it does only call once for a normal page load (at least in my app)).
So InteractiveServer may call
OnInitializedAsync()
twice if pre-rendering is on. And I want that lightening fast initial render. And there is no way to know if a call is the pre-render or post-render call. Or possibly the only-render call.To handle this I have seen three main approaches suggested:
OnInitializedAsync()
may not return for several seconds. Is that ok?OnInitializedAsync()
, pre & post. Then read the DB and populate the page inOnAfterRenderAsync(true)
. But this means initializing as part of the rendering process. And then forcing a re-render of the page. Possibly multiple re-renders as I populate multiple components in a page. Is this ok?[CascadingParameter] HttpContext HttpContext{ get; set; }
where it is!= null
for pre-render. Is this reliable and will it be reliable in future versions?thanks - dave
Beta Was this translation helpful? Give feedback.
All reactions