Skip to content

Instantly share code, notes, and snippets.

@saurabhnemade
Last active August 13, 2019 03:36
Show Gist options
  • Save saurabhnemade/8d01c4accdf7f54b0ab6f0a0d52bd4a7 to your computer and use it in GitHub Desktop.
Save saurabhnemade/8d01c4accdf7f54b0ab6f0a0d52bd4a7 to your computer and use it in GitHub Desktop.
Dynamic Redux Reducer - 2
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