Although I'm newbie of redux as well as of RTK, I'm just starting redux project with RTK as if you start with Spring Boot not Spring these days.
I want to dynamically inject reducers on demand on redux toolkit(RTK). I realized that I need to keep track of current reducers to make it. I expected my store from RTK would have a reference to them, but unfortunately it seems it doesn't have such a property.
While I found this module that seems to do the job, but it seems I have to go back to the days before RTK was created to make it work.
import {createStore, createReducer, Slice, Reducer, AnyAction, combineReducers} from "@reduxjs/toolkit";
const Store = createStore<any, any, any, any>(createReducer({}, () => {}));
const reducers: {
[key: string]: Reducer<any, AnyAction>;
} = {};
export const injectReducer = (slice: Slice) => {
reducers[slice.name] = slice.reducer;
Store.replaceReducer(combineReducers(reducers));
};
Even more (maybe I just don't know the way) type definitions will go insane.
Is there any way to make this?
The answer could be in a store enhancer form:
const injectReducerEnhancer: StoreEnhancer = (createStore) => (...args) => {
const store = createStore(...args);
store.asyncReducers = {};
store.injectReducer = (key, asyncReducer) => {
store.asyncReducers[key] = asyncReducer;
store.replaceReducer(createReducer(store.asyncReducers));
};
return store;
};
function createReducer(asyncReducers) {
return combineReducers({
...staticReducers,
...asyncReducers
});
};
configutreStore({
enhancers: [injectReducerEnhancer],
// ...
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With