react-boilerplate/redux-injectors

Feature request: reducer ejection

tawanorg opened this issue · 1 comments

Hi

The problem I am working on is making apps work under micro frontend architecture. One challenge I am working on is I like to completely reject a reducer from the Redux store when users leave the page aka componentWillUnmount

I've done the PoC as following below

// injectReducer.js
const useInjectReducer = ({ key, reducer }) => {
  const store = useStore();
  const [isInjected, setIsInjected] = React.useState(false);

  React.useLayoutEffect(() => {
    getInjectors(store).injectReducer(key, reducer);
    setIsInjected(true);

    return () => {
      // To remove a reducer from Redux store
      getInjectors(store).rejectReducer(key);
    };
  }, []);

  return isInjected;
};
// reducerInjectors.js

export function ejectReducerFactory(store, isValid) {
  return function ejectReducer(key, reducer) {
    if (!isValid) checkStore(store)
    
   if (
      !Reflect.has(store.injectedReducers, key)
    )
      return;
      
     delete store.injectedReducers[key]
     store.replaceReducer(store.createReducer(store.injectedReducers));
  };
}
export default function getInjectors(store) {
  checkStore(store);

  return {
    injectReducer: injectReducerFactory(store, true),
    ejectReducer: ejectReducerFactory(store, true),
  };
}
  

Do you think, does this worth a pull request?

Hi @tawanorg , I just want to know why you close this issue. I see this feature should be a part of the reducer injection of redux