diff --git a/lib/potent-reducer.js b/lib/potent-reducer.js index 453bc63..1567712 100644 --- a/lib/potent-reducer.js +++ b/lib/potent-reducer.js @@ -16,22 +16,6 @@ export const usePotentReducer = options => { return [state, _thunks] } -/** A ReducerStore Factory that uses React.context - * Used to make a Store accessible through multiple components - */ -export const createStore = options => { - const context = createContext(null) - const { Consumer } = context - const Provider = ({ children }) => { - const store = usePotentReducer(options) - return React.createElement(context.Provider, { value: store }, children) - } - const useStore = () => useContext(context) - const useSelector = selector => selector(useContext(context)[0]) - const useDispatch = () => useContext(context)[1] - return { Provider, Consumer, useStore, useSelector, useDispatch } -} - /** Turn a reducer definition object to a function * @param {Object} reducer: Object definition of a reducer: {: (state, payload) => } * @param {Object} options @@ -86,6 +70,35 @@ function patchDispatch(dispatch, type) { } } +/** A ReducerStore Factory that uses React.context + * Used to make a Store accessible through multiple components + */ +export const createStore = options => { + const context = createContext(null) + const { Consumer } = context + const Provider = ({ children }) => { + const store = usePotentReducer(options) + return React.createElement(context.Provider, { value: store }, children) + } + const useStore = () => useContext(context) + const useSelector = selector => { + const val = selector(useContext(context)[0]) + options.warnOnUndefinedSelect && assertSelectedExists(val) + return val + } + const useDispatch = () => useContext(context)[1] + return { Provider, Consumer, useStore, useSelector, useDispatch } +} + +function assertSelectedExists(value) { + console.warn(`A selector returned undefined. +This indicates that you tried to access a state property that does not exist. +To turn these messages off use {"warnOnUndefinedSelect": false} in options`) + console.groupCollapsed('Trace') + console.trace() + console.groupEnd() +} + /** Log action inspired by redux-logger */ const logger = ({ prevState, action, nextState }) => { const css = color => `color: ${color}; font-weight: bold;`