mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-15 12:20:31 +00:00
26 lines
583 B
TypeScript
26 lines
583 B
TypeScript
import React, { 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;
|
|
}
|