Last active
December 8, 2023 18:53
-
-
Save twofingerrightclick/ff3a0d26efe8b6c07becaee336f5e5ad to your computer and use it in GitHub Desktop.
An example of how to handle null when using OnInitializedAsync to fetch data to display in a Blazor component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>@Config?.WelcomeMessage</h2> | |
@code { | |
protected ConfigObject? Config { get; set; } | |
protected int RenderCount { get; set; } | |
protected override async Task OnInitializedAsync() | |
{ | |
Console.WriteLine(RenderCount); // 0 | |
// await "triggers" the next steps in the component lifecycle, such as rendering | |
Config = await ReturnHelloWorldAsync(); | |
Console.WriteLine(RenderCount); // 1 | |
} | |
protected override void OnAfterRender(bool firstRender) | |
{ | |
RenderCount++; | |
} | |
protected async Task<ConfigObject> ReturnHelloWorldAsync() | |
{ | |
await Task.Delay(100); // Simulating some asynchronous operation | |
return new ConfigObject(); | |
} | |
protected class ConfigObject | |
{ | |
public string WelcomeMessage => "Hello World!"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>@Config.WelcomeMessage</h2> | |
@code { | |
protected ConfigObject Config { get; set; } = null!; | |
protected int RenderCount { get; set; } | |
// completes before rendering part of lifecycle and can be used like a constructor for setting properties | |
protected override void OnInitialized() | |
{ | |
Console.WriteLine(RenderCount); // 0 | |
Config = new(); | |
Console.WriteLine(RenderCount); // 0 | |
} | |
protected override void OnAfterRender(bool firstRender) | |
{ | |
RenderCount++; | |
} | |
protected class ConfigObject | |
{ | |
public string WelcomeMessage => "Hello World!"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment