Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceReducer on @reduxjs/toolkit

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?

like image 596
Changdae Park Avatar asked May 14 '26 17:05

Changdae Park


1 Answers

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],
  // ...
})
like image 98
D.H.Lolo Avatar answered May 17 '26 05:05

D.H.Lolo