Blazor Server: obtain and cascade down some global parameters via _Host.cshtml vs App.razor?

Viewed 318

In my Blazor Server app, I want to pass down some parameters that are available to all components, so naturally I want to define these at the root/top level.

Examples: a user's claim (user ID etc), and a user's subscription data (paid vs free etc).

Here the subscription data needs to be queried from the database.

I realized that there are actually two places where I can achieve this:

Method 1. I can query for all the data I need in _Host.cshtml, and pass it to the root Blazor component via the param-Variable syntax. Example:

@{
    var myData = await MyDataService.GetMyDataAsync();
    ....
}

 <component type="typeof(App)" render-mode="ServerPrerendered" param-MyData="myData" />

Once this is done, my App.razor component will receive [Parameter] MyData, and then MyData will be in turn provided as CascadingValue to all the child components.

Method 2. Alternatively, I can do the data queries from within App.razor's code behind itself, then pass it down. The problem with this approach is that I found it a bit tricky to deal with the Blazor page life cycles, to ensure that the parameter value is retrieved and available in time for every child component to use, and without doing unnecessary extra queries and StateHasChanged calls.

So given my use case, I feel #1 seems easier and more straight forward. It guarantees that the queries are executed once per user session, and the parameters are already available by the time the root component starts rendering.

But is there any drawback of using the Razor host page this way?

0 Answers
Related