Blazor Server-Side variable doesn't update after function call because of OnAfterRenderAsync

Viewed 304

I have have a Server-Side Blazor app with a simple index.razor Page. My goal is to read sessionStorage and use it's content. But for now I am trying to make baby steps to understand what is going on.

This is the html

@inject Blazored.SessionStorage.ISessionStorageService sessionStorage

<button @onclick="TestInc">TEST</button>
<h1>@tutu</h1>

I only have a text to show the the number and a simple button to increment my value And this is the code

@code {
    private int tutu = 0;
    public string sNom;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            bool isConnected = await sessionStorage.GetItemAsync<bool>("isConnected");
            //if (!isConnected)
            //{
            //    NavManager.NavigateTo("/Login", forceLoad: true);
            //}
            sNom = sessionStorage.GetItemAsync<string>("Nom").Result;
        }
    }
    private void TestInc()
    {
        tutu += 1;
    }
}

For some reason, the code works fine if I comment the whole OnAfterRenderAsync function. The page will show the counter and update it when it I click on the button. However if I have the function OnAfterRenderAsync uncommented and do it's thing, the counter is not updated at all and if I put a breakpoint inside TestInc it never reaches it.

I am relatively new to Blazor so I might be missing something really obvious here.

What I really would like to achieve is get sessionStorage variable (a username for example) and display it inside my HTML without having to click on a button or reloading the page

2 Answers

The solution is simple:

//sNom = sessionStorage.GetItemAsync<string>("Nom").Result;
sNom = await sessionStorage.GetItemAsync<string>("Nom");
  1. never use .Result or .Wait()
  2. always aim for an unbroken 'chain' of awaits
  3. treat "lacks await" and "is not awaited" Warnings as if they were Errors.

this will work if your sessionStorage has a item called Nom

sNom = await sessionStorage.GetItemAsync<string>("Nom");
Related