How to use Local Storage in Blazor
Introduction
Local storage, a key-value data structure available within modern web browsers, enables applications to store data in the browser's memory. This data persists even after the user closes the browser or navigates away from the page. It serves as a temporary storage solution for non-sensitive static data, reducing server load, and improving performance by minimizing server calls.
Blazor applications can access local storage using JavaScript interop, allowing seamless integration with browser-based storage. In this article, we'll explore how Blazor leverages local storage to enhance user experiences and optimise application performance.
Video Explanation
Demo
Here is the demo of the final product, You can see how Blazor utilizes the local storage:
What's happening here?
We're developing an application to demonstrate the use of local storage. Our goal is to show how to add, update, and delete data from local storage effectively. To achieve this, I've designed a simple form with three buttons, as shown in demo above. Our application manages a list of programming languages, including fields such as Name, Creator, and Year.
Here's how it works:
LocalStorage Service
Let's begin by creating a service to encapsulate local storage functionality. The LocalStorageService class facilitates interaction with the browser's local storage through JavaScript.
//Listing 1: LocalStorageSerive.cs
using Microsoft.JSInterop;
namespace BlazingLocalStorage.LocalStorage
{
public class LocalStorageService
{
private readonly IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task AddItem(string key, string value)
{
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, value);
}
public async Task RemoveItem(string key)
{
await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", key);
}
public async Task<string> GetItem(string key)
{
return await _jsRuntime.InvokeAsync<string>("localStorage.getItem", key);
}
}
}
Explanation of listing 1:?
In order to represent our form fields, let's create a model called ProgrammingLanguage:
//Listing 2: ProgrammingLanguage.cs
public class ProgrammingLanguage
{
public string Name { get; set; }
public string Creator { get; set; }
public int Year { get; set; }
}
ProgrammingLanguage Service?
The ProgrammingLanguageService acts as a mediator between the UI and the local storage service. It manages programming languages stored in local storage and provides methods for adding, retrieving, and deleting language entries.
//Listing 3: ProgrammingLanguageService.cs
using System.Text.Json;
namespace BlazingLocalStorage.LocalStorage
{
public class ProgrammingLanguageService
{
private readonly LocalStorageService _localStorageService;
public ProgrammingLanguageService(LocalStorageService localStorageService)
{
_localStorageService = localStorageService;
}
public async Task AddOrUpdateLanguageAsync(string languageName, ProgrammingLanguage languageToAdd)
{
var jsonLanguage = JsonSerializer.Serialize(languageToAdd);
await _localStorageService.AddItem(languageName, jsonLanguage);
}
public async Task DeleteLanguageAsync(string languageName)
{
await _localStorageService.RemoveItem(languageName);
}
public async Task<ProgrammingLanguage> GetLanguageAsync(string languageName)
{
ProgrammingLanguage language = null; ;
var jsonLanguage = await _localStorageService.GetItem(languageName);
if (jsonLanguage != null)
{
language = JsonSerializer.Deserialize<ProgrammingLanguage>(jsonLanguage);
}
return language;
}
}
}
The component
The UI component, LanguageManagement.razor, enables users to add, edit, and remove programming language entries. It interacts with the ProgrammingLanguageService to perform these operations seamlessly.
//Listing 4: LanguageManagement.razor
@page "/"
@using LocalStorage
@inject ProgrammingLanguageService LanguageService
<div class="row">
<div class="col-md-4">
<h3>Add, Edit or Remove Language</h3>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" @bind="Language.Name" id="name" />
</div>
<div class="form-group">
<label for="creator">Creator:</label>
<input type="text" class="form-control" @bind="Language.Creator" id="creator" />
</div>
<div class="form-group">
<label for="year">Year:</label>
<input type="text" class="form-control" @bind="Language.Year" id="year" />
</div>
<div class="form-group mt-3">
<button class="btn btn-primary" @onclick="SaveLanguage">Save</button>
<button class="btn btn-danger" @onclick="DeleteLanguage">Delete</button>
<button class="btn btn-secondary" @onclick="LoadLanguage">Load</button>
</div>
</div>
</div>
@code {
private ProgrammingLanguage Language = new ProgrammingLanguage();
private async void SaveLanguage()
{
await LanguageService.AddOrUpdateLanguageAsync(Language.Name, new ProgrammingLanguage()
{
Name = Language.Name,
Creator = Language.Creator,
Year = Language.Year
});
}
private async void DeleteLanguage()
{
await LanguageService.DeleteLanguageAsync(Language.Name);
Language.Name = Language.Creator = string.Empty;
Language.Year = 0;
}
private async void LoadLanguage()
{
Language = await LanguageService.GetLanguageAsync(Language.Name);
StateHasChanged();
}
}
The UI looks like image 1 shown below.
Conclusion
Local storage operates entirely on the client side, reducing the need for frequent server calls to fetch or update data. This makes it an ideal choice for storing user preferences, application settings, theme preferences, language preferences, and display options that need to be accessed across sessions.
Now that we understand what to store in local storage, it's important to be aware of what not to store. Local storage is not a secure storage solution for sensitive or confidential information, such as passwords, credit card details, or personally information.
By leveraging local storage in Blazor applications, you can enhance user experiences. With proper usage, local storage can significantly improve the responsiveness?of web applications.
Consultor .NET en CHANGE CENTER
4 个月Is it possible to customize the maximum storage size?
Co-Creator : Codefrydev | C# | Asp.Net Core | Blazor | .NET MAUI | Fullstack Developer
1 年blazing stuff ?? ?? ??