Search code examples
asp.net-coreblazorblazor-server-side

Best way to preload data in blazor server


I want to do something similar to what I can do in React. In React, before the app renders I can call a function that requests data from the server (data that will be used everywhere in the application). Something like the company id for example.

So an idea I had was to have all my pages require authentication. So a non authenticated user will get in, authentication will send the user to the scaffolded identity razor pages, then the razor pages will send the user back through the return URL.

I want to be able to load my favority company id (stored in DB) before any blazor component renders after the redirect and I want to render a loader until it is finished and I can access my company id everywhere in my application safely without it being null.

Mostly I want to understand the execution order in rendering in blazor server to know where I can pre-load data before the user can interact with my application. I thoug

Which would be the best place to do this in a blazor server application?

I have two possible places where I could do this preloading, either on App.razor

<MaterialStyles />

<ThemeProvider Theme="@Theme.Light" />

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

So I could add a code block here, but I am not sure if I can know if my user is authenticated at this moment in execution. I wonder if I could do this instead in the layout file of my application or if there is a better place for this preloading to occur.


Solution

  • Since the initial request to a Blazor Server App is not performed via SignalR connection, but through HTTP, you can perform various tasks, including retrieval of data from a data store, and pass this data to your Blazor app in the form of attributes set on the component Html taghelper, residing in the _Host.cshtml file.

    Note that while you the code in the _Host.cshtml file is executed you are in the Razor Pages App domain, not Blazor.

    You should define appropriate properties in the App component to receive the passed values set in the component Html taghelper. Now you can use these values or / and store them in the local storage or session storage for a later use.

    Here's a link to my answer how to do that. Please, don't hesitate to ask for help if you need...