contextism
Version:
New way to use React Context
40 lines (35 loc) • 1.53 kB
JavaScript
import { useContext as useContext$2, createContext, createElement } from 'react';
var useContext = function (context) {
if (!context) {
throw new Error('react-use-context-hook: ❌ pass a context to the useState hook.');
}
return useContext$2(context);
};
var useStore = function (state, dispatch) {
if (!state || !dispatch) {
throw new Error('react-use-context-hook: ❌ pass two contexts to the useAllState hook.');
}
return [
useContext$2(state),
useContext$2(dispatch)
];
};
var createStore = function (defaultState) {
var stateContext = createContext(defaultState);
var dispatchContext = createContext(undefined);
return {
stateContext: stateContext,
dispatchContext: dispatchContext,
useStateContext: function () { return useContext(stateContext); },
useDispatchContext: function () { return useContext(dispatchContext); },
useStore: function () { return useStore(stateContext, dispatchContext); },
Provider: function (_a) {
var state = _a.state, dispatch = _a.dispatch, children = _a.children;
return (createElement(stateContext.Provider, { value: state },
createElement(dispatchContext.Provider, { value: dispatch }, children)));
}
};
};
var useContext$1 = function (context) { return useContext(context); };
var useStore$1 = useStore;
export { createStore, useContext$1 as useContext, useStore$1 as useStore };