1

Here is what I've been doing in my Blazor server application -- pretty much every page needs to load some content by calling an API. I've been adding this async function inside the OnInitializedAsync() method.

However, recently, I've been reading articles that this is not the right place to do. It should've been done in the OnAfterRenderAsync() event. Here is an article talking about it towards the bottom: SpinKit Loading

I would like to know have I been doing it wrong? If so, why? Are any initial page data fetch should all be done in OnAfterRenderAsync()?

Thanks!

Franky
  • 704
  • 8
  • 22

2 Answers2

2

You only have to call it in OnAfterRenderAsync if you are calling JavsScript. If you don't have any [Parametet] properties, or you only need to call the API once then OnInitializedAsync is fine. If it is a page with route parameters, or a component with [Parameter] properties and the call to the API depends on those properties, then you need to call it in SetParametersAsync.

Peter Morris
  • 16,193
  • 8
  • 71
  • 124
0

As you know in Blazor server application every lifecycle methods are called twice, so best practice would be calling database, long-running calculation and calling JavaScript will be in OnAfterRenderAsync/OnAfterRender method, check if it renders first time using firstRender flag, otherwise calling database/long-running calculation will be called unnecessary twice. for example

protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
               // calling database/long-running calculation/calling JavaScript
        }
    }

If you want to read more about methods lifecycle: https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-3.1

Mofaggol Hoshen
  • 598
  • 6
  • 18