Last active
August 13, 2019 03:36
-
-
Save saurabhnemade/8d01c4accdf7f54b0ab6f0a0d52bd4a7 to your computer and use it in GitHub Desktop.
Dynamic Redux Reducer - 2
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 { createStore as _createStore, combineReducers } from 'redux'; | |
import rootReducer from ‘./rootReducer’; | |
const dynamicActionGenerator = () => { | |
return '@@TEST-REDUCER-VALIDITY/' + Math.random().toString(36).substring(7).split('').join('\\'); | |
}; | |
const isValidReducer = (reducer, throwError = false) => { | |
if (typeof reducer !== 'function') { | |
if (throwError) { | |
throw new Error('You did not passed a valid reducer. A reducer must be a function with two parameters state and action'); | |
} else { | |
return false; | |
} | |
} | |
const initialState = reducer(undefined, {type: dynamicActionGenerator()}); | |
if (typeof initialState === 'undefined') { | |
if (throwError) { | |
throw new Error('Reducer must return state!!!.'); | |
} else { | |
return false; | |
} | |
} | |
return true; | |
} | |
const createStore = (initialReducer, initialState, enhancers) => { | |
let store = _createStore(initialReducer, initialState = {}, enhancers); | |
store.asyncReducers = {}; | |
store.attachReducer = (storeKeyPath, dynamicReducer) => { | |
if (isValidReducer(dynamicReducer)) { | |
store.asyncReducers = { ...store.asyncReducers, [storeKeyPath]: dynamicReducer }; | |
} else { | |
throw new Error(`The reducer at "${storeKeyPath}" is not a valid reducer`); | |
} | |
}; | |
return store; | |
}; | |
export { createStore }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment