Suchiman / BlazorDualMode

Demo on how to run dynamically in client or server side mode
MIT License
145 stars 24 forks source link

OnInitializedAsync getting called twice on launch #11

Closed JoelW187 closed 4 years ago

JoelW187 commented 4 years ago

I implemented your dual-mode on a simple Blazor app that has a client Index.cshtml page with an OnInitializedAsync(). The OnInitializedAsync() makes an async call to initialize some data.

When I run the app in "pure" client Blazor (without your dual-mode code) everything runs correctly. But when I add the dual-mode code, the OnInitializedAsync() gets called twice regardless of wether I'm in client or server mode. I'm assuming it's getting called once on the RenderComponentAsync in _Host.cshtml and once when the Index.cshtml page actually loads. Any suggestions on how to prevent this?

I've well versed in client Blazor but haven't really worked in server Blazor yet so it's probably something I'm not quite getting about the server mechanisms.

Great code, btw!

Suchiman commented 4 years ago

I haven't tested it but my theory is that it gets prerendered on the server which is the first invocation of OnInitializedAsync and then gets rendered a second time, either at the moment wasm is loaded or the websocket connection for the server side mode gets established.

I think you should be able to turn off the first OnInitializedAsync call from prerendering by disabling prerendering at the cost of slower perceived loading time. For that, change @(await Html.RenderComponentAsync<Client.App>(RenderMode.ServerPrerendered)) in the _Host.cshtml into @(await Html.RenderComponentAsync<Client.App>(RenderMode.Server)).

JoelW187 commented 4 years ago

@Suchiman you were correct - changing from ServerPrerendered to Server fixed the problem. Thanks!