esehigs
esehigs

Reputation: 5

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.‎

Upvotes: 0

Views: 1665

Answers (1)

Mister Magoo
Mister Magoo

Reputation: 8964

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);
  }
}

Upvotes: 2

Related Questions