'Blazor await LocalStorage.GetAsync dont wait

I would like to read information from the LocalStorage within a .razor file and then execute further source code on the basis of this. The problem is that he doesn't wait when reading from the LocalStorage.‎

@{
    var loggedIn = IsLoggedIn();

    if (loggedIn.Result)
    {
       // do something
    }
}
private async Task<bool> IsLoggedIn()
{
    var result = await LocalStorage.GetAsync<Account>("AccountInfo");
    _account = result.Value;

    return string.IsNullOrEmpty(_account?.Name);
}

As soon as it reaches the "await LocalStorage.GetAsync" and I continue using debugger, "if (loggedIn.Result)" is called without waiting for the result of the await.‎

‎What could be the reason?‎

‎Best regards and thank you for ideas.‎



Solution 1:[1]

You are not awaiting the call to IsLoggedIn, so as soon as the code hits the await LocalStorage.GetAsync call, execution continues on the main thread.

You cannot use await in razor markup/inline code, so you need to do things differently.

try something like this instead:

@if (loggedIn)
{
 // do something
}

@code 
{
  bool loggedIn = false;

  protected override async Task OnInitializedAsync()
  {
    loggedIn = await IsLoggedIn();
    StateHasChanged();
  }

  private async Task<bool> IsLoggedIn()
  {
    var result = await LocalStorage.GetAsync<Account>("AccountInfo");
    _account = result.Value;

    return string.IsNullOrEmpty(_account?.Name);
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mister Magoo