Skip to content

Instantly share code, notes, and snippets.

@Nauthiz-Jera
Created October 30, 2018 15:30
Show Gist options
  • Save Nauthiz-Jera/471b1ae8bdbf5d080aedd72fa51cd50b to your computer and use it in GitHub Desktop.
Save Nauthiz-Jera/471b1ae8bdbf5d080aedd72fa51cd50b to your computer and use it in GitHub Desktop.
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