Home > Software engineering >  Why do I have to click on my top bar to activate local storage in blazor?
Why do I have to click on my top bar to activate local storage in blazor?

Time:01-02

To clarify my question some more here is my code:

<!--this is the MainLayout.razor page -->
@inherits LayoutComponentBase
@inject Blazored.LocalStorage.ILocalStorageService localStorage
<PageTitle>T</PageTitle>
<MudLayout>
        
    <MudAppBar Elevation="1" Dense="false" Color="Color.Primary">
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Secondary" Edge="Edge.Start" OnClick="@((e) => DrawerToggle())" />
     </MudAppBar>
     <MudDrawer @bind-Open="_drawerOpen" ClipMode="DrawerClipMode.Always" Elevation="2" Color="Color.Secondary">
        <NavMenu></NavMenu>
     </MudDrawer>
     <MudMainContent> 
         @text 
         @Body
    </MudMainContent>
</MudLayout>

@code {
    public bool Authed { get; set;} = false;
    bool _drawerOpen = false;
    public string text { get; set;} = "";

    protected override void OnInitialized()
    {
        base.OnInitialized();
        AutoInitLocalStorage();

    }

    void DrawerToggle()
    {
        _drawerOpen = !_drawerOpen;
    }

    private async void AutoInitLocalStorage()
    {
         bool authed = await localStorage.GetItemAsync<bool>("authorized");
         Authed = authed;
         text = Authed.ToString();
    }
}

when I run this nothing happens until I click on my top bar button, once I do the field @text shows up above the @body and is true, why is this? how can I make it run immediately? I tried to set @text to anything above the async local storage call and it shows up immediately.

CodePudding user response:

The page is loaded before the 'authed' is retrieved from localStorage because of the await statement without returning a task that OnInitialized (s/b OnInitializedAsync) waits for.

Try the following:

Replace OnInitialized with:

protected override async Task OnInitializedAsync()
{
    await AutoInitLocalStorage();
}

and change AutoInitLocalStorage to (note the 'Task' return type):

async Task AutoInitLocalStorage()
{
     bool authed = await localStorage.GetItemAsync<bool>("authorized");
     Authed = authed;
     text = Authed.ToString();
}
  • Related