Search code examples
c#blazor

OnInitializedAsync() in blazor


I have used OnInitializedAsync() in my code. In that hook, I am fetching data. In markup, I have checked whether data is null or not. But I found that data checked is executed before the onInitalizedAsync() triggered. Meanwhile, after getting data too, data checked is executed.

I have checked the blazor documents but struggling to find why it triggered at first.

<Component1>
  @if (Data != null)
      {
        @foreach (var item in Data) {
             <Component2>
        }
       }
</Componet1>

@code{
  protected override async Task OnInitializedAsync() {
       Data = //data from dataBase
  }
}

I need to execute data checked only after data fetch. Can anyone guide me to fix this issue?


Solution

  • The data check has to happen first because something has to be rendered before the OnInitializedAsync method. So in case the OnInitializedAsync takes a long time to load the data, the user already sees something and not just a blank page.

    Why do you want the data check only after the data fetch?

    As a workaround you can create a local variable bool dataIsLoaded = false; and only after loading data in OnInitializedAsync you can set it to true. Then in the data check do: @if (dataIsLoaded && Data != null)