required-react-context
Version:
A simple React Context wrapper that throws an error if it is used without being provided
2 lines • 1.69 kB
JavaScript
import u,{createContext as v,useContext as c,useDebugValue as C}from"react";var d=Symbol.for("required-react-context/unset-value");function N(e){return typeof e!="string"?"":e.charAt(0).toUpperCase()+e.slice(1)}function p(e,t){if(!e)throw new Error(t)}var x=(e,t)=>`${e}: context value is not set. Use ${t} to set the value.`,l=(e,{providerName:t,contextName:r})=>Object.assign(v(e),{providerName:t,displayName:r}),f=(e,t)=>{for(let[r,s]of Object.entries(e))p(typeof s=="string",`${t}: Expected ${r} to be a string. Got: ${typeof s}`);e.hookName&&p(e.hookName.startsWith("use"),`${t}: hookName must start with "use". Got: ${e.hookName}`)},T=({name:e,contextName:t=`${N(e)}Context`,providerName:r=`${N(e)}Provider`,providerProp:s=e,consumerName:i=`${N(e)}Consumer`,hookName:a=`use${N(e)}`})=>({name:e,contextName:t,providerName:r,providerProp:s,consumerName:i,hookName:a});function k(){return{with(e){f(e,"createRequiredContext");let{contextName:t,providerName:r,providerProp:s,consumerName:i,hookName:a}=T(e),m=l(d,{providerName:r,contextName:t});return{[t]:m,[r](o){return u.createElement(m.Provider,{value:o[s]},o.children)},[i](o){return u.createElement(m.Consumer,null,n=>(p(n!==d,x(i,r)),o.children(n)))},[a](){let o=c(m);return p(o!==d,x(a,r)),C(o),o}}}}}function G(e){return{with(t){f(t,"createOptionalContext");let{contextName:r,providerName:s,providerProp:i,consumerName:a,hookName:m}=T(t),o=l(e,{providerName:s,contextName:r});return{[r]:o,[s](n){return u.createElement(o.Provider,{value:n[i]},n.children)},[a](n){return u.createElement(o.Consumer,{...n})},[m](){let n=c(o);return C(n),n}}}}}export{d as a,p as b,x as c,k as d,G as e};
//# sourceMappingURL=chunk-ER4PD4M6.js.map