@future-widget-lab/react-context-provider
Version:
A helper for creating React providers with an associated custom hook.
59 lines (54 loc) • 1.63 kB
JavaScript
import * as React from 'react';
function _objectWithoutPropertiesLoose(r, e) {
if (null == r) return {};
var t = {};
for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
if (-1 !== e.indexOf(n)) continue;
t[n] = r[n];
}
return t;
}
/**
* @description
* Use this helper to create a hook that uses a specific context.
*/
var createContextHook = function createContextHook(options) {
var name = options.name,
context = options.context;
var useHook = function useHook() {
var provided = React.useContext(context);
if (!provided) {
throw new Error("Trying to use " + name + " hook out of its context.");
}
return provided;
};
Object.defineProperty(useHook, 'name', {
value: "use-" + name + "-context-provider"
});
return useHook;
};
var _excluded = ["children"];
var createContextProvider = function createContextProvider(options) {
var name = options.name,
useGetState = options.useGetState;
var context = React.createContext({});
var ContextProvider = function ContextProvider(_ref) {
var children = _ref.children,
rest = _objectWithoutPropertiesLoose(_ref, _excluded);
var state = useGetState(rest);
return React.createElement(context.Provider, {
value: state
}, typeof children === 'function' ? children(state) : children);
};
var hook = createContextHook({
name: name,
context: context
});
ContextProvider.displayName = name + "-context-provider";
return {
ContextProvider: ContextProvider,
hook: hook
};
};
export { createContextProvider };
//# sourceMappingURL=react-context-provider.esm.js.map