C
C#8mo ago
NonUnique

HTML renders before/during OnInitializedAsync - Blazor server side (no SignalR)

Hi, I want to use Blazor to return static html with no .NET interactivity so SignalR is disabled. this is Test.Razor
@page "/test"
<h3>Test</h3>
@foreach (var line in lines) @*<- lines not set yet*@
{
<p>@line</p>
}
@code {
private List<string>? lines = null;
protected override async Task OnInitializedAsync()
{
await Task.Delay(1000);
lines = ["1", "2"];
await base.OnInitializedAsync();
}
}
@page "/test"
<h3>Test</h3>
@foreach (var line in lines) @*<- lines not set yet*@
{
<p>@line</p>
}
@code {
private List<string>? lines = null;
protected override async Task OnInitializedAsync()
{
await Task.Delay(1000);
lines = ["1", "2"];
await base.OnInitializedAsync();
}
}
Task.Delay would be my real IO call. Issue is that HTML C# portion starts executing before lines is being set. So it errors out on foreach. https://blazor-university.com/components/component-lifecycles/ it's here early in lifecycle. If I add @if (lines is not null) it returns properly but does it mean that in backend it keeps redrawing on changing values until OnInitializedAsync is fully done? If I need to handle each value arriving from async methods as possibly null then I sort of make my code work with no data and on real bad data I wouldn't not get 500 to indicate bad data. For RazorComponentResult in minimal API responses I suppose I could do async methods and pass results as parameters but then all logic is lost from .razor page. Now as I think this might enable child/parent communication before returning HTML so it's intended and I should always assume anything IO will be missing initially (to be aware in child parameters or in parent should be covered with if before making render child component)? Maybe there is some true static server side mode? I'm very new to Blazor but have sense how this would be useful on SPA/SignalR streams.
1 Reply
NonUnique
NonUniqueOP8mo ago
got bit rusty with FE, that's exactly how I needed to write code in the past on Angular to protect against errors during page draw. I use Blazor in non standard way and expect Blazor to comply with me. At least in this situation ?? [] makes it easy. So all guarantees have to be done within @code block.
Want results from more Discord servers?
Add your server