mrpmorris / Fluxor

Fluxor is a zero boilerplate Flux/Redux library for Microsoft .NET and Blazor.
MIT License
1.26k stars 145 forks source link

Best approach to a global state store ? #232

Closed mattrandle closed 2 years ago

mattrandle commented 2 years ago

Hi,

Wonder if you could provide some direction for best approach to a global state store.

My requirement is to load static data from an API (after auth) via a state store and use that data across multiple pages.

Currently, in each page im having to dispatch the action to load the state in OnInitialized

Dispatcher.Dispatch(new LoadGlobalStateAction());
ActionSubscriber.SubscribeToAction<GlobalStateLoadedAction>(this, GlobalStateLoaded);

And in my EffectMethod just dont make the API call if its already loaded,

[EffectMethod(typeof(LoadGlobalStateAction))]
public async Task LoadGlobalState(IDispatcher dispatcher)
{
    if (!state.Value.Loaded)
    {
        var state = await myDashApiClient.GetStateAsync(false);
        dispatcher.Dispatch(new GlobalStateLoadedAction(state));
    }
    dispatcher.Dispatch(new GlobalStateLoadedAction(state.Value.State));
}

(I need the GlobalStateLoaded callback to trigger in each page to set other values)

This works but is this the best approach ?

Thanks for the great lib btw - generally working a treat for a large blazor web assembly app

mrpmorris commented 2 years ago

Write an effect that reacts to StoreInitializedAction, that happens only once and is the first action dispatched.