From 9a5618031697c5867b1707eda9092288c3a7d61c Mon Sep 17 00:00:00 2001 From: Marcello Lamonaca Date: Mon, 9 Aug 2021 13:46:06 +0200 Subject: [PATCH] Add State Manegement Notes --- DotNet/ASP.NET/Blazor.md | 74 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/DotNet/ASP.NET/Blazor.md b/DotNet/ASP.NET/Blazor.md index 88264d3..a8cff95 100644 --- a/DotNet/ASP.NET/Blazor.md +++ b/DotNet/ASP.NET/Blazor.md @@ -257,6 +257,80 @@ Project } ``` +## State Management + +### Blazor WASM + +```cs +// setup state singleton +builder.Services.AddSingleton(); +``` + +```cs +// StateContainer singleton +using System; + +public class StateContainer +{ + private int _counter; + + public string Property + { + get => _counter; + set + { + _counter = value; + NotifyStateChanged(); // will trigger StateHasChanged(), causing a render + } + } + + public event Action OnChange; + + private void NotifyStateChanged() => OnChange?.Invoke(); +} +``` + +```cs +// component that changes the state +@inject StateContainer State + +// Delegate event handlers automatically trigger a UI render + + +@code { + private void HandleClick() + { + State.Property += 1; // update state + } +} +``` + +```cs +// component that should be update on state change +@implements IDisposable +@inject StateContainer State + +

Property: @State.Property

+ +@code { + + // StateHasChanged notifies the component that its state has changed. + // When applicable, calling StateHasChanged causes the component to be rerendered. + + protected override void OnInitialized() + { + State.OnChange += StateHasChanged; + } + + public void Dispose() + { + State.OnChange -= StateHasChanged; + } +} +``` + ## Javascript/.NET Interop [Call Javascript from .NET](https://docs.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet)