|
|
|
|
|
by bob1029
2327 days ago
|
|
Global state in one happy place is basically what we've done with Blazor. Instead of using cascading parameters and other ridiculously complex ways of passing state around, we inject stateful services as scoped dependencies per client request. These are effectively just POCO models with a functional interface for mutating state. Then, we take dependencies on these throughout the web application (I.e. within each component or page). An example of one of these used heavily throughout would be UserSessionService. Certain aspects of the application may have their own dedicated state machines like LoginService (which is utilized only during the login process). LoginService takes a CTOR dependency on UserSessionService and it all plays together really nicely via Microsoft's DI. We've even wired events from server-side directly into these services so its not just for handling the client-specific interactions either. Integrating server-side events is trivial. It felt a little weird at first, but it seems we are moving in a much more sustainable direction now. I can actually test my UI state machines in complete isolation from an actual browser. Also, because they are simply .NET implementations, we can reuse these for other aspects of the application. |
|
We have a "service layer" for React made up of state-machine-based services (although reactive services based on RxJS observables works as well). We also created associated custom hooks that allow developers to easily "inject" a service into their React component (use use React's Context API for our "DI container"). From there they can read the service state, or send events to it to trigger behaviour that is encapsulated in the service itself.
We even have the same "most used" service; a UserSession service manages OAuth based login flow and session management.
The best part of this approach is that our service layer started in an Angular based proof-of-concept before we lifted-and-shifted it all into React.
[1] https://xstate.js.org/