Blazored LocalStorage

repository·main·Indexed 23 days ago

https://github.com/blazored/localstorage

A library for Blazor applications providing access to the browser's LocalStorage API with automatic serialization and deserialization. It offers ILocalStorageService for asynchronous operations across Blazor WebAssembly and Server, and ISyncLocalStorageService for synchronous operations in WebAssembly. Features include custom JSON serializer support, JS Interop streaming for large objects in Blazor Server, and testing extensions for bUnit.

Tokens
2.2K
Snippets
14
Records
14
Agent score
30%

What's inside Blazored LocalStorage

  1. Enable JS Interop Streaming for large objects in Blazor Server

    main

    In Blazor Server, JS Interop calls are limited by the SignalR message size (default 32KB). To store or retrieve objects larger than this, use the streaming implementation.

    1. Register the streaming service: services.AddBlazoredLocalStorageStreaming();
    2. Add the required JavaScript file to your _App.razor: <script src="_content/Blazored.LocalStorage/Blazored.LocalStorage.js"></script>
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddBlazoredLocalStorageStreaming();
    }
  2. Install Blazored LocalStorage

    main

    You can install the Blazored LocalStorage package via the .NET CLI, NuGet Package Manager in Visual Studio, or by adding a PackageReference directly to your .csproj file.

    dotnet add package Blazored.LocalStorage
  3. Use Open Iconic's SVG Sprite

    main

    The SVG sprite allows you to load all icons in a single request. To use an icon, reference the sprite file and the specific icon ID within a <use> tag inside an <svg> element.

    Styling

    • Sizing: Set equal width and height on the <svg> tag.
    • Coloring: Set the fill property on the <use> tag.

    Tip: For better styling, add a general class to the <svg> tag and a unique class to the <use> tag.

    <svg class="icon">
      <use xlink:href="open-iconic.svg#account-login" class="icon-account-login"></use>
    </svg>
    .icon {
      width: 16px;
      height: 16px;
    }
    
    .icon-account-login {
      fill: #f00;
    }
  4. Setup Blazored LocalStorage in Blazor Server

    main

    In Blazor Server, register the service in your _Startup.cs file using AddBlazoredLocalStorage().

    Important: Due to pre-rendering in Blazor Server, you cannot perform JS interop (and thus access LocalStorage) until the OnAfterRender or OnAfterRenderAsync lifecycle methods have been called.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddBlazoredLocalStorage();
    }
  5. Test Blazored LocalStorage with bUnit

    main

    The Blazored.LocalStorage.TestExtensions package provides an in-memory implementation of local storage for use with the bUnit testing library. This allows for realistic component testing without a real browser environment.

    1. Install Blazored.LocalStorage.TestExtensions.
    2. Use the AddBlazoredLocalStorage() extension method on your TestContext.
    public class IndexPageTests : TestContext
    {
        [Fact]
        public async Task SavesNameToLocalStorage()
        {
            // Arrange
            const string inputName = "John Smith";
            var localStorage = this.AddBlazoredLocalStorage();
            var cut = RenderComponent<BlazorWebAssembly.Pages.Index>();
    
            // Act
            cut.Find("#Name").Change(inputName);
            cut.Find("#NameButton").Click();
                
            // Assert
            var name = await localStorage.GetItemAsync<string>("name");
                
            Assert.Equal(inputName, name);
        }
    }
  6. Setup Blazored LocalStorage in Blazor WebAssembly

    main

    In Blazor WebAssembly, register the service in your Program.cs file using AddBlazoredLocalStorage().

    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");
    
        builder.Services.AddBlazoredLocalStorage();
    
        await builder.Build().RunAsync();
    }
  7. Configure JSON Serializer Options

    main

    You can customize the System.Text.Json settings used by the library by passing a configuration delegate to AddBlazoredLocalStorage during service registration.

    builder.Services.AddBlazoredLocalStorage(config =>
        config.JsonSerializerOptions.WriteIndented = true
    );
  8. Use a custom JSON serializer

    main

    To use a different JSON library (like Newtonsoft.Json), implement the Blazored.LocalStorage.Serialization.IJsonSerializer interface and register it in your DI container using builder.Services.Replace.

    builder.Services.AddBlazoredLocalStorage();
    builder.Services.Replace(ServiceDescriptor.Scoped<IJsonSerializer, MySerializer>());