contextism
Version: 
New way to use React Context
46 lines (39 loc) • 1.61 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
var useContext = function (context) {
    if (!context) {
        throw new Error('react-use-context-hook: ❌ pass a context to the useState hook.');
    }
    return React.useContext(context);
};
var useStore = function (state, dispatch) {
    if (!state || !dispatch) {
        throw new Error('react-use-context-hook: ❌ pass two contexts to the useAllState hook.');
    }
    return [
        React.useContext(state),
        React.useContext(dispatch)
    ];
};
var createStore = function (defaultState) {
    var stateContext = React.createContext(defaultState);
    var dispatchContext = React.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 (React.createElement(stateContext.Provider, { value: state },
                React.createElement(dispatchContext.Provider, { value: dispatch }, children)));
        }
    };
};
var useContext$1 = function (context) { return useContext(context); };
var useStore$1 = useStore;
exports.createStore = createStore;
exports.useContext = useContext$1;
exports.useStore = useStore$1;