-
Notifications
You must be signed in to change notification settings - Fork 25.1k
Labels
BlazorPri3Source - Docs.msDocs Customer feedback via GitHub IssueDocs Customer feedback via GitHub Issuedoc-enhancement
Description
[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.
- ID: ae14b3e3-3271-b919-9e0a-6f317a6b2d2d
- Version Independent ID: e5e1273b-195e-5da1-b4aa-66bbcff1425b
- Content: ASP.NET Core Blazor state management
- Content Source: aspnetcore/blazor/state-management.md
- Product: aspnet-core
- Technology: aspnetcore-blazor
- GitHub Login: @guardrex
- Microsoft Alias: riande
Metadata
Metadata
Assignees
Labels
BlazorPri3Source - Docs.msDocs Customer feedback via GitHub IssueDocs Customer feedback via GitHub Issuedoc-enhancement
Type
Projects
Status
Done