Created
October 30, 2018 15:30
-
-
Save Nauthiz-Jera/471b1ae8bdbf5d080aedd72fa51cd50b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import PropTypes from 'prop-types' | |
import hoistNonReactStatics from 'hoist-non-react-statics' | |
import isEmpty from 'lodash/isEmpty' | |
import { createUpdatedReducer } from '../store' | |
import { setupNewReducers } from './reducer-injector-helper.utility' | |
const getDisplayName = ({displayName, name}) => `withReducer(${displayName || name || 'component'})` | |
export function injectReducerFactory (store) { | |
return function injectReducer (reducerCollection) { | |
const { injectedReducers, replaceReducer } = store | |
/* | |
* get current injected reducers and the a collection of reducers you will like to | |
* add to the the redux store | |
*/ | |
const updatedReducers = setupNewReducers(injectedReducers, reducerCollection) | |
if (!isEmpty(updatedReducers)) { | |
replaceReducer(createUpdatedReducer(updatedReducers)) | |
} | |
} | |
} | |
export const getInjectors = (store) => ({ | |
injectReducer: injectReducerFactory(store) | |
}) | |
export default (reducerCollection) => { | |
return WrappedComponent => { | |
class ReducerInjector extends Component { | |
static WrappedComponent = WrappedComponent; | |
static contextTypes = { | |
store: PropTypes.object.isRequired | |
} | |
static displayName = getDisplayName(WrappedComponent) | |
constructor (props, context) { | |
super() | |
this.injectors = getInjectors(context.store) | |
const { injectReducer } = this.injectors | |
injectReducer(reducerCollection) | |
} | |
render () { | |
return <WrappedComponent {...this.props} /> | |
} | |
} | |
return hoistNonReactStatics(ReducerInjector, WrappedComponent) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment