How do I initialize variables at startup in a Blazor webassembly app?

Viewed 4847

In UWP, I would programmatically initialize display variables at startup so that the initial display was what I wanted, for example, values based on the day of the year value. I can't crack where to replicate this in my otherwise working Blazor webassembly app. I currently put up default values and ask the user to click a button, that calculates and updates to the values I want to display and on we go.

I would have thought there's a standard, easy way to do this, but given how Blazor pieces are constructed on the fly in order to render as web pages, maybe not? Thanks!

2 Answers

This isn't specific to Blazor, but in any class you can create code in the constructor of your component/

Here I have a Chat component, that I break up into

Chat.razor
Chat.razor.cs  

The chat.razor.cs you create by adding a class with the same name as your component, then add the word partial to make it a partial class:

partial class Chat : IBlazorComponent, IBlazorComponentParent, IDisposable

Note: The interfaces are just for my app, I am just showing the line with partial. really are you need it:

partial class Chat

Then in my constructor I created:

public Chat()
{
    // Perform initializations for this object
    Init();
}

I just call a method, you don't have to:

My Init method:

 public void Init()
 {
     // do your initializations 
 }

Or you can use OnInitializedAsync

protected override async Task OnInitializedAsync()
{
    // load the Categories (example)
    this.Categories = await HelpCategoryService.GetHelpCategoryList()
}

Or here is another I use sometimes: OnAfterRender

protected override void OnAfterRender(bool firstRender)
{
    if (firstRender)
    {
        ...
    }
}

Documentation for that is here:

https://docs.microsoft.com/en-us/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1

Maybe that gives you some ideas. Not sure about Standard, every use case is different.

Note: I have never used Blazor Web Assembly, only server side Blazor, so not sure what is specific to WASM, but I know constructors work in any C# class.

I assume you want to have global Variables for your app:

  1. Create a Initialize service that initializes your static data.

    public class InitializeService { public InitializeService() { MyStaticDataClass.Variable1 == "Pling"; MyStaticDataClass.Variable1 == "GlobalPlong"; } }

  2. In startup services.AddSingleton().

Your MyStaticDataClass vars will now be available from your app and pages

Related