Live Chat Icon For mobile
Live Chat Icon

How do I use IndexedDB in Blazor WebAssembly?

Platform: Blazor| Category : General, WebAssembly

IndexedDB is used for the client-side storage of data and files. Follow these steps to use IndexedDB in Blazor WebAssembly:

  1. Create a Blazor WebAssembly app and install the Reshiru.Blazor.IndexedDB.Framework NuGet package using the NuGet package manager.

  2. Set up the IIndexedDbFactory configuration service in your Program.cs file and set it as scoped.

    using Blazor.IndexedDB.Framework;
    public class Program
       public static async Task Main(string[] args)
               builder.Services.AddScoped<IIndexedDbFactory, IndexedDbFactory>();

  3. Now add the properties inside the class to store and process data in the Data folder.

    using Blazor.IndexedDB.Framework;
    using Microsoft.JSInterop;
    using System.ComponentModel.DataAnnotations;
    namespace {{Your_App_Name}}.Data
        public class IndexDb : IndexedDb
            public IndexDb (IJSRuntime JSRuntime, string name, int version) : base(JSRuntime, name, version) { }
         public IndexedSet<Employee> Employees { get; set; }
        public class Employee
            public long Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }

  4. Add the namespace for the IndexedDB in _Import.razor file.

    @using Blazor.IndexedDB.Framework
    @using {{Your_App_Name}}.Data

  5. Add the Razor component to add and store the data using IndexedDB in the Index.razor file.

    @page "/"
    @inject IIndexedDbFactory DbFactory
    @if (employ != null)
        <table class="table">
                    <th>First name</th>
                    <th>Last name</th>
                @foreach (var employee in employ)
                        <td><button @onclick="@(() => DeleteForm(employee))">Delete</button></td>
        <legend>Add new person</legend>
        <EditForm Model="@newEmployee" OnValidSubmit="@SaveForm">
            <InputText placeholder="First name" @bind-Value="@newEmployee.FirstName" />
            <InputText placeholder="Last name" @bind-Value="@newEmployee.LastName" />
            <button type="submit">Add</button>
            <p><ValidationSummary /></p>
            <DataAnnotationsValidator />
    @code {
        Employee newEmployee = new Employee();
        List<Employee> employ;
        protected async Task OnInitializedAsync()
            using var db = await DbFactory.Create<ExampleDb>();
            employ = db.Employees.ToList();
        async Task SaveForm()
            // Add employee details.
        async Task DeleteForm(Employee person)
            // Delete the employee.

  6. Refer to this blog for more details.

Share with

Related FAQs

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

Please submit your question and answer.