I have two react apps which each has it's own redux store (inside ASP.Net Core, but I don't think that's relevant). I found that I had quite a lot of duplicate code between the two apps so I made a Ui.Common Project for the shared code between the two projects. In that scope I introduced a commonStore that each of the two apps uses as well as their own store.
As per the docs I initialize the commonStore on it's own React-Context and the connect calls reference that same context when the commonStore is required. For the initialization of the stores I do:
const store = ReduxStore.configureStore(history);
const commonStore = CommonStore.configureStore();
ReactDOM.render(
<Provider store={store}>
<Provider store={commonStore} context={CommonContext}>
<ConnectedRouter history={history} children={routes} />
</Provider>
</Provider>,
document.getElementById('react-app')
);
Config for the CommonStore
public configureStore() {
const windowIfDefined = typeof window === 'undefined' ? null : window as any;
// If devTools is installed, connect to it
const devToolsExtension = windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__ as () => StoreEnhancer;
const createStoreWithMiddleware = compose(devToolsExtension ? devToolsExtension() : <S>(next: StoreEnhancerStoreCreator<S>) => next)(createStore);
const store = createStoreWithMiddleware(rootReducer()) as Store<CommonAppState>;
return store;
}
And these are my "helper" methods for interacting with the commonStore:
export function rootReducer(): Reducer<CommonAppState> {
return combineReducers<CommonAppState>({
app: appReducer,
userSettings: userSettingsReducer
});
}
export const CommonContext = React.createContext<ReactReduxContextValue>(undefined);
/** A connect wrapper to connect specifically to the common redux store. */
export function commonConnect(mapStateToProps?, mapDispatchToProps?, mergeProps?, options?: ConnectOptions) {
if (!options) {
options = {};
}
options.context = CommonContext;
return connect(mapStateToProps, mapDispatchToProps, mergeProps, options);
}
In one of the apps (Ui.WebApp) this works as expected, the two stores work independently and everything is nice.
In the second app (Ui.Management) the commonConnect doesn't seem to work correctly. In the redux dev-tools I can see that the store is there, gets initialized and has a default initial state. Also, the dispatches (from mapDispatchToProps) I execute on the store are there and update the store accordingly.
But in every single mapStateToProps the state is always undefined.
Most of the components consuming the commonStore actually "live" in Ui.Common and as they work in Ui.WebApp but not in Ui.Management, the problem most likely is not located within the Ui.Common project.
The two partial reducers definitely have their default set, as otherwise it wouldn't work in any of the two apps.