A library to provide access to local storage in Blazor applications
There is currently an issue with ASP.NET Core Razor Components apps (not Blazor). They are unable to import static assets from component libraries such as this one.
You can still use this package, however, you will need to manually add the JavaScript file to your Razor Components wwwroot
folder. Then you will need to reference it in your index.html
.
Alternatively, there is a great package by Mister Magoo which offers a solution to this problem without having to manually copy files.
You can install from Nuget using the following command:
Install-Package Blazored.LocalStorage
Or via the Visual Studio package manger.
First, you will need to register local storage with the service collection in your startup.cs file
public void ConfigureServices(IServiceCollection services)
{
services.AddBlazoredLocalStorage();
}
This is an example of using local storage in a .cshtml file
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@functions {
protected override async Task OnInitAsync()
{
await localStorage.SetItem("name", "John Smith");
var name = await localStorage.GetItem<string>("name");
}
}
The APIs available are
- SetItem()
- GetItem()
- RemoveItem()
- Clear()
- Length()
- Key()
All APIs in ILocalStorageService
are async
If you are using Blazor (not Razor Components), you can choose to instead inject Blazored.LocalStorage.ISyncStorageService
to opt into a synchronous API that allows you to avoid use of async
/await
. For either interface, the method names are the same.
Note: Blazored.LocalStorage methods will handle the serialisation and de-serialisation of the data for you.