Skip to content

Blazor: In-memory state container as cascading parameter #27296

@lonix1

Description

@lonix1

[EDIT by guardrex: The current approach for the in-memory state container service is located at In-memory state container service.]

The "In-memory state container service" section shows a state container as a service.

For simple app-wide stuff, it is simpler to use a cascading value. I posted a related question (with working code) to StackOverflow. (UPDATE: "MrC" posted another very nice solution.)

For example, working code:

AppState.razor

<CascadingValue Value="this">
  @ChildContent
</CascadingValue>

@code {

  private bool _isDirty;

  [Parameter] public RenderFragment ChildContent { get; set; }

  protected override async Task OnAfterRenderAsync(bool firstRender) {
    await base.OnAfterRenderAsync(firstRender);
    if (firstRender) {
      await LoadStateFromLocalStorage();
    }
    if (!firstRender && _isDirty) {
      await SaveStateToLocalStorage();
      _isDirty = false;
    }
  }

  private bool _isDarkMode;
  public bool IsDarkMode {
    get {
      return _isDarkMode;
    }
    set {
      if (value == _isDarkMode) return;
      _isDarkMode = value;
      StateHasChanged();
      _isDirty = true;
    }
  }

  //other properties...

  private async Task LoadStateFromLocalStorage() {
    Console.WriteLine("LOADED!");
    await Task.CompletedTask;
  }

  private async Task SaveStateToLocalStorage() {
    Console.WriteLine("SAVED!");
    await Task.CompletedTask;
  }

}

App.razor

<AppState>
  <Router>
    ...
  </Router>
</AppState>                                                          

MyComponent.razor

<!--- markup --->

@code {
  [CascadingParameter] public AppState AppState { get; set; }

  //...
}

It would be nice to have that as another section, e.g. "In-memory state container as cascading parameter".


Document Details

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

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions