Aspnetcore.docs: Blazor WASM State Management topic

Created on 14 May 2020  ·  13Comments  ·  Source: dotnet/AspNetCore.Docs

Are there plans with the 3.2 release to add examples / best practices for proper state management in Blazor Web Assembly?

I know this is all Blazor Server, but given that Blazor WebAssembly is a common pattern too, I figure this is a fair question :)


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

5.0 Blazor P1 Source - Docs.ms doc-idea

Most helpful comment

As for the categories (your last question), maybe we should hold on for now. Let's roll the simple state management doc and then see how community will react and tell us what more they will need.

All 13 comments

@taylorchasewhite While we wait for triage and engineering guidance ...

  • WRT state management in secured WASM apps (i.e., not losing state across sign in/sign out), I'm working on that now on https://github.com/dotnet/AspNetCore.Docs/pull/18652.
  • WRT just general state management, Idk if Microsoft.AspNetCore.ProtectedBrowserStorage works in WASM apps. @mkArtakMSFT may know, or you can certainly try to use it and see what happens. 🤞 Worse-case tho, one would implement their own state container service and have some methods to read and restore state from local/session storage.

@mkArtakMSFT, if we proceed on this one, the options are:

  • Change this doc to cover both WASM and Server in separate high-level sections (H2s) with the current Blazor Server content rolling in under the Server section.
  • Create a new doc for state management in WASM. Seems like a better choice. However, we would need a node for this approach, perhaps with an Overview topic for the node with some common coverage ...

    • State management (ToC node)
    • Blazor WebAssembly

      • UID: blazor/state-management/webassembly

      • Physical: blazor/state-management/webassembly.md

    • Blazor Server

      • UID: blazor/state-management/server

      • Physical: blazor/state-management/server.md

I'll need to know either way ...

  • More about Microsoft.AspNetCore.ProtectedBrowserStorage working in WASM apps ... I can test and find that out on my own tho.
  • Which state management strategies should we cover in addition to creating a state management container for their app?

    • Cookies

    • URL

    • IndexedDB

    • Caching

    • Other 3rd party key-value or dB storage options (we could at least have a link list to other client-side 3rd party tech, like the way we do for config providers)

@guardrex, ProtectedBrowserStorage support is now in (https://github.com/dotnet/aspnetcore/pull/23553). @MackinnonBuck can you share a small sample showing how to use the new ProtectedBrowserStorage?

Also, I do like the idea of having a separate node for Blazor WebAssembly state management: Create a new doc for state management in WASM, as you referred to it.

As for the categories (your last question), maybe we should hold on for now. Let's roll the simple state management doc and then see how community will react and tell us what more they will need.

Microsoft.AspNetCore.ProtectedBrowserStorage has been moved to Microsoft.AspNetCore.Components.Web.Extensions in dotnet/aspnetcore and has undergone some small API changes. ProtectedBrowserStorage relies on a Blazor server feature and does not work in WebAssembly. The existing docs for ProtectedBrowserStorage have some good examples of how to use it, but the API has changed slightly (especially regarding GetAsync()). Here's an updated example:

@using Microsoft.AspNetCore.Components.Web.Extensions
@inject ProtectedLocalStorage ProtectedLocalStore

... rendering code goes here ...

@code {
    private int? currentCount;
    private bool isConnected = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // When execution reaches this point, the first *interactive* render
            // is complete. The component has an active connection to the browser.
            isConnected = true;
            await LoadStateAsync();
            StateHasChanged();
        }
    }

    private async Task LoadStateAsync()
    {
        var result = await ProtectedLocalStore.GetAsync<int>("prerenderedCount");
        currentCount = result.Success ? result.Value : 0;
    }

    private async Task IncrementCount()
    {
        currentCount++;
        await ProtectedSessionStore.SetAsync("count", currentCount);
    }
}

Blazor server feature and does not work in WebAssembly

Then, the options are down to ...

  • Convert the doc to cover both WASM and Server given the overlap in approaches in the Where to persist state section and with possible 3rd party libs. Sections that would pertain to one or the other clearly marked within the topic.
  • Current Choice: New doc for WASM (and a node to hold both topics), and it will have similar coverage to what's in the Where to persist state section, possibly with INCLUDES file(s) to avoid any coverage duplication. We probably can enhance the coverage ... some useful examples would be nice within reason ... "within reason" meaning that I have a lot of balls in the air prior to and during 5.0 release, so I don't want to get too crazy bogged down.
  • Don't address WASM at this time and only use this issue to fix up the current coverage for Blazor Server.

@mkArtakMSFT I'm working on this issue now. I think we should try a single _pivot_ topic for this at first. I can use INCLUDES for common content. Let's give it a shot. I think it would reduce our burden for:

  • A new node and Overview.
  • More complicated content split between/among topics.
  • More messing about with the ToC.
  • Another redirection file entry.

If it doesn't work out on review, I can set up a new PR with the node-topic approach.

As a reminder on pivots, see the Tooling doc, which performs pivots on OS. For this work, we'd pivot our State management topic on Blazor WebAssembly and Blazor Server instead of OS ...

https://docs.microsoft.com/aspnet/core/blazor/tooling

UPDATE Yes! ... the draft is looking good with pivots. The draft is done. I'll sleep on it and turn it in on Tuesday morning. btw -- Solving both tasks on this issue:

  • Surface content for WASM.
  • Update the protected storage bits for 5.0.

@MackinnonBuck ... You mentioned (and showed) a change for local storage GetAsync. Is the current coverage on _session storage_ still accurate? ...

To recover the currentCount data if the user returns to the Counter component later, including if the user is on an entirely new circuit, use ProtectedSessionStore.GetAsync:

protected override async Task OnInitializedAsync()
{
    currentCount = await ProtectedSessionStore.GetAsync<int>("count");
}

UPDATE ... I made quite a few changes to the draft updates this morning. I'll need to 💤🛌 sleep on it one more time. I hope to have the PR up on Wednesday morning.

@guardrex The new changes apply for both local storage and session storage.

Ok ... I'll likely need to make one more commit then. ~Stand-by before you review.~

:smile: lol ... I forgot ...... tomorrow. I need to sleep on it one more night. I'll make the changes, and they'll be on the PR in the morning.

UPDATE: _Done!_

@scottaddie ❓ ... For the new pivot group blazor-hosting-models, I'll go with ...

- id: blazor-hosting-models
  title: Blazor Hosting Model
  prompt: Choose a Blazor hosting model
  pivots:
    - id: webassembly
      title: Blazor WebAssembly
    - id: server
      title: Blazor Server

I noticed that prefixing the OSes in the operating-systems group with os- is overkill. It's a common and meaningless prefix for a whole topic that uses pivot groups on OS. It seems to make more sense to drop the os-. After all, I don't plan on using hosting-model-webassembly and hosting-model-server for the blazor-hosting-models pivots. The only reason those os- prefixes are there is because the file that I stole from the other repo had them. I propose that we do this for that group ...

- id: windows
  title: Windows
- id: linux
  title: Linux
- id: macos
  title: macOS

_Now_ is the time ⏰ to make this change if we're going to make it, while there's only one doc, the Blazor Tooling topic, that uses pivot groups. I'll make the change if you concur.

UPDATE: I'm going to go ahead and get this PR set up now. We can review the pivot file on the PR and revert if necessary.

@guardrex Your zone pivots proposal sounds good to me.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Raghumu picture Raghumu  ·  3Comments

madelson picture madelson  ·  3Comments

nenmyx picture nenmyx  ·  3Comments

sonichanxiao picture sonichanxiao  ·  3Comments

royshouvik picture royshouvik  ·  3Comments