typesafe-context-hook
Version:
A react-typescript utility for creating typesafe React context hooks. It provides a function that takes a name and a hook, and returns an object with a custom hook, a provider component, and a higher-order component. The custom hook can only be used withi
36 lines (35 loc) • 1.38 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
function typesafeContextHook(name, hook) {
const Context = (0, react_1.createContext)(null);
const Provider = (_a) => {
var { children } = _a, args = __rest(_a, ["children"]);
const value = hook(args);
return (0, jsx_runtime_1.jsx)(Context.Provider, { value: value, children: children });
};
function useNamedContextHook() {
const value = (0, react_1.useContext)(Context);
if (value === null) {
throw new Error(`use${name}Context must be used within a ${name}Provider`);
}
return value;
}
return {
[`use${name}Context`]: useNamedContextHook,
[`${name}Provider`]: Provider,
};
}
exports.default = typesafeContextHook;