What is the best way in Blazor to initialize a page that hits the DB to initialize itself

David Thielen 3,211 Reputation points
2023-06-12T20:39:32.6366667+00:00

Hi all;

What I learned in this question is I want to set render-mode="Server" in _Host.cshtml. This way the page is rendered once.

But... this is also the slowest way to render the page. If the code in my OnInitializedAsync() is hitting the DB, then nothing will be rendered until I've read everything from the DB.

For this case, is it better to read in that data in OnAfterRenderAsync(true)? In this case the page will be rendered with no data, and then the data will fill.

And, for my case at least, and variables that impact layout in terms of what's visible, what's enabled, etc. I can set in OnInitializedAsync() without hitting the DB. So tables/grids will grow once I populate the data, but other than that, it would just be fields being populated with their initial data.

So what is normally done in this case?

thanks - dave


Update:

Here's a simple example. And this shows two things:

  1. If you order your code correctly, the experience for the user is the same both ways.
  2. In OnInitializedAsync() put all the code that takes no time first, then the DB and API calls. That way the initial render will be as complete/correct as can be when first rendered.
Developer technologies | .NET | Blazor
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 78,006 Reputation points Volunteer Moderator
    2023-06-12T23:22:56.48+00:00

    You should re-read how Blazor works. You don't render a page.

    Blazor builds a component render tree. On component property change, the effected component (and its children) are rebuilt. then the blazor render tree updates are sent to the browser, where the client copy of the render tree is updated. The client then updates the dom based on changes to the render tree.

    component renders should be very fast, as they will happen on any state change. no async events are allowed during the render, and no expensive calls should be made.

    anything expensive should be async and moved to OnAfterRenderAsync. you may need to use a queue and debounce.

    say you were writing an autocomplete. char input triggers a db lookup call. during the lookup 2 more chars may be typed. this is two addition renders while the db call is in progress. you do not want to start two more database queries, you want to do the next lookup based on the lastest input. often you would use a holdout timer and debounce.

    see: https://blazor-university.com/components/render-trees/


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.