Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading