Blazor cross component state mutation
What’s the best way to implement a theme switcher/toggle where one component on the layout gets the initial theme mode state, lets you switch, saves new value to db, but also needs to communicate the change to the rest of the component tree?
Currently I am trying an approach using SignalR and hubs to send a notification where another component picks up the state change and passes it down the heirarchy as a cascading parameter.
This works well although I’d rather not rely on SignalR if a singleton state manager with simple StateHasChanged invocation can happen. But I’m not sure how to do that given that the state is per user.
Thought?
3 Replies
My thought are: SignalR will work as the save to db can happen even if the hub is down and the next time the tree rerender, the state will be updated
So if the hub communication fails, it’s not the end of the world, it would just look broke cause the state doesn’t match the new toggle value
But I’d like the page the match the new state as soon as possible
but in case someone has a better idea, heres what i have:
```cs
<div>
// html for selecting theme mode (light
</div>
@code {
[
Quite a lot of libraries like MudBlazor implement this. You could look at their code.
I know. We aren’t allowed to use it