Add warning on undefined select

This commit is contained in:
Alfred Melch 2020-02-01 21:21:01 +01:00
parent 366c338528
commit 5a32f3de0c

View File

@ -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: {<type>: (state, payload) => <newState>}
* @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;`