reducerInjectors.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import invariant from 'invariant'
  2. import { isEmpty, isFunction, isString } from 'lodash'
  3. import checkStore from './checkStore'
  4. import createReducer from '../reducers'
  5. export function injectReducerFactory (store, isValid) {
  6. return function injectReducer (key, reducer) {
  7. if (!isValid) { checkStore(store) }
  8. invariant(
  9. isString(key) && !isEmpty(key) && isFunction(reducer),
  10. '(app/utils...) injectReducer: Expected `reducer` to be a reducer function'
  11. )
  12. // Check `store.injectedReducers[key] === reducer` for hot reloading when a key is the same but a reducer is different
  13. if (
  14. Reflect.has(store.injectedReducers, key) &&
  15. store.injectedReducers[key] === reducer
  16. ) {
  17. return
  18. }
  19. store.injectedReducers[key] = reducer // eslint-disable-line no-param-reassign
  20. store.replaceReducer(createReducer(store.injectedReducers))
  21. }
  22. }
  23. export default function getInjectors (store) {
  24. checkStore(store)
  25. return {
  26. injectReducer: injectReducerFactory(store, true)
  27. }
  28. }