I've used the Blazor Fluxor library extensively in my Blazor webassembly (standalone) application, along with Fluxor.Persist to maintain state between browser sessions. I'd like to create a 'demo' version that has certain feature states pre-initialized with predefined data, which will be unmodifiable by the user, based on a feature switch flag set in the configuration.
I'm wondering how best to go about this.
- I had looked into setting feature initialization based on the flag, which I was doing in
Program.cs
beforehost.RunAsync()
, by resolving the service that fetches the predefined data from JSON files. The issue I found here is I believe that running awaitbuilder.Build()
, and then resolving the 'fetch data' service and running it, conflicts with the Fluxor feature initialization that runs at the same time, and can end up running while the 'fetch data' service awaits any calls to retrieve JSON data (I might be wrong here, but this was my impression).
Secondly, doing it this way means I have to create static instances of the predefined state to pass into each feature initialization method, as apparently dependency injection into a feature state is a bad approach:
public static PredefinedState {get; private set;}
public async Task LoadDefaultsIfDemo()
{
if (!IsDemoSetup)
{
return;
}
var predefinedState = await _httpClient.GetFromJsonAsync<PredefinedState>("demo/predefinedStateData.json");
PredefinedState = predefinedState;
}
- The second option, which is a little over my head, is to create a middleware class that sets the feature state, along the lines of:
internal class SetupMiddleware : Middleware
{
readonly IDemoDataProvider _demoDataProvider;
public SetupMiddleware(IDemoDataProvider demoDataProvider)
{
_demoDataProvider = demoDataProvider;
}
public override async Task InitializeAsync(IDispatcher dispatcher, IStore store)
{
var predefined = await _demoDataProvider.GetDemoData();
store.Features["DemoFeature"].RestoreState(predefined);
}
}
internal interface IDemoDataProvider
{
Task<object> GetDemoData();
}
- The third option is creating separate actions that just set the state and don't trigger any further effects that the existing actions to set state do - this would involve creating a quite a few new actions and reducers for only setting predefined state, and they'd have to run before my
MainLayout
runs as I have a component wrapping@Body
that runs checks on the existing state and fires update actions to make sure all feature states are correctly set and updated - not all of my feature sub state is persisted across browser sessions, so this is what this is for.
Does anyone have any advice on the right approach here?
I tried pre-initializing state before host.RunAsync()
, I've looked into the options for middleware and adding actions that set state before the MainLayout
runs