Search code examples
blazorstateblazor-server-sidepre-renderingblazor-state-management

Blazor state is FE or BE?


I would like to know if the saved state is FE or server side? I am using the following tutorial which works. https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/persist-component-state?view=aspnetcore-7.0

I am trying to avoid the double database hit due to double component initialization on render mode = pre rendering.

  1. Basically right now on first initialize we collect from database.
  2. And on second initialize we collect from "application state"

My question is the saved application state is server side? Would the Browser have to request the content again to the server? (doesn't this mean double traffic?) Or the application state remains on user computer and when we request it on second initialize we don't call the server again.

@code {
    public string bgcolor { get; set; } = "#2F4858";
    public Website? Website { get; set; }
    private PersistingComponentStateSubscription _subscription;


    protected override async Task OnInitializedAsync()
    {
        _subscription = ApplicationState.RegisterOnPersisting(PersistWebsite);

        if (ApplicationState
           .TryTakeFromJson<Website>("Website", out var storedWebsite))
        {
            Website = storedWebsite;
        }
        else
        {
            Website = websiteService.GetWebsite(MyNavigationManager.Uri);            
        }
    }

    private Task PersistWebsite()
    {
        ApplicationState.PersistAsJson("Website", Website);
        return Task.CompletedTask;
    }

    void IDisposable.Dispose()
    {
        _subscription.Dispose();
    }
}

I tried to search info online, but failed to find something useful.


Solution

  • No, the saved application state is part of the HTML. Oversimplified the state you persist is JSON-encoded inside the HTML the server sends to the client.

    Check the HTML code of your application with a persisted application state and look for your properties ;)