Live Chat Icon For mobile
Live Chat Icon

How do I access browser local storage in Blazor?

Platform: Blazor| Category : General, Lifecycle, Tips and Tricks

To access browser  localStorage in Blazor apps, write a custom code or use a third party package. The difference between localStorage and sessionStorage  is: The localStorage is scoped to the user’s browser. If the user reloads the page or closes and reopens the browser, the state persists. Session storage is similar to local storage but the data in the session storage will be cleared after the session.

The  Blazored.LocalStorage package can be used to access the browser’s local storage in Blazor. For this you need to install the package and add the service to the application.

[Program.cs]

using Blazored.LocalStorage; 
…
builder.Services.AddBlazoredLocalStorage(); 

[index.razor]

@page "/" 
@inject Blazored.LocalStorage.ILocalStorageService localStorage 
<h2>@Name</h2> 
<button @onclick="Clear">Clear LocalStorage</button> 

@code { 
    public string? Name; 
    protected override async Task OnAfterRenderAsync ( bool firstRender ) 
    { 
        await localStorage.SetItemAsync("ID", "20019"); 
        await localStorage.SetItemAsync("Name", "John Smith"); 
        Name = "ID: " + await localStorage.GetItemAsync<string>("ID") + "Name : " + await localStorage.GetItemAsync<string>("Name"); 
    } 
    public async void Clear () 
    { 
        //this will clear the local storage 
        await localStorage.ClearAsync(); 
    } 
} 

To access the local storage using the OnInitialized method, disable the ServerPrerender in _Host.cshtml. 

Reference link: https://chrissainty.com/blazored-local-storage-v0-3-0-released/ 

View Sample in GitHub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.