Module exposing: createSafeContext
// Source: https://github.com/alibey-10/indie-ui | License: MIT | Copyright Indie UI
// Provided via justclaw.it.com; keep this notice with the code.
import { createContext, useContext } from 'react';
export function createSafeContext<ContextValue>(errorMessage: string) {
const Context = createContext<ContextValue | null>(null);
const useSafeContext = () => {
const ctx = useContext(Context);
if (ctx === null) {
throw new Error(errorMessage);
}
return ctx;
};
const Provider = ({
children,
value,
}: {
value: ContextValue;
children: React.ReactNode;
}) => <Context.Provider value={value}>{children}</Context.Provider>;
return [Provider, useSafeContext] as const;
}
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key