Live Chat Icon For mobile
Live Chat Icon

How do I save and load data within a component in Blazor?

Platform: Blazor| Category : Components, General

By utilizing browser storage in Blazor, you can effectively save and load data within a component. In the following example, you can see how the counter value is updated with a button click and the count value is stored in the local storage of the browser. When you refresh the page, the saved data will be loaded from the browser’s local storage.


@page "/"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage LocalStorage

@if (isCount)
    <p>Current count: <strong>@currentCount</strong></p>
    <button class="btn btn-primary" @onclick="IncrementCount">Increment</button>

@code {
    private int currentCount;
    private bool isCount;

    protected override async Task OnAfterRenderAsync(bool firstRender)
        if (firstRender)
            isCount = true;
            // Get the count value into browser local storage.
            var countValue = await LocalStorage.GetAsync<int>("countValue");
            // Loaded the browser local storage value to currentCount.
            currentCount = countValue.Success ? countValue.Value : 0;

    private async Task IncrementCount()
        // Set the count value in browser local storage.
        await LocalStorage.SetAsync("countValue", currentCount);

Refer to this link for more details.

Share with

Related FAQs

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

Please submit your question and answer.