0

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

Yogi
  • 6,241
  • 3
  • 24
  • 30
esehigs
  • 5
  • 1
  • Please post in English. – H H Mar 28 '22 at 10:40
  • 1
    Related SO question: [How to call asynchronous method from synchronous method](https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c) – Yogi Mar 28 '22 at 12:09

1 Answers1

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);
  }
}
Mister Magoo
  • 7,452
  • 1
  • 20
  • 35
  • The `.Result` in the original code does an implied (a)wait. – H H Mar 29 '22 at 06:07
  • That was not the question - it was basically "why does the code reach that line before expected" and the implied question - "how do I do this?", and that is why I gave this answer. And as `.Result` blocks the calling thread, it is not a good idea to use it in a razor inline code block. I would have expected a warning at the very least - but I have never written this code, so don't know if it does warn? – Mister Magoo Mar 29 '22 at 06:50
  • Yes, it's not clear if there is a problem or even a warning. Getting code out of the markup is the right direction. – H H Mar 29 '22 at 07:14