Files
portainer/app/react/utils/context.tsx
T
LP B 0c2f07988a feat(app/sources): source create view (#2680)
Co-authored-by: Chaim Lev-Ari <chaim.lev-ari@portainer.io>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 21:34:46 +03:00

34 lines
913 B
TypeScript

import {
PropsWithChildren,
createContext as reactCreateContext,
useContext as reactUseContext,
} from 'react';
/**
* Reduce the boilerplate code to create a custom context and provider hook
* @param displayName Display name of the Context in react inspector
* @returns A Provider and custom hook for this context
*/
export function createContext<TContext>(displayName: string) {
const Context = reactCreateContext<TContext | null>(null);
Context.displayName = displayName;
return { Provider, useContext };
function Provider({
children,
context,
}: PropsWithChildren<{ context: TContext }>) {
return <Context.Provider value={context}>{children}</Context.Provider>;
}
function useContext() {
const context = reactUseContext(Context);
if (context === null) {
throw new Error(`should be nested under Provider - ${displayName}`);
}
return context;
}
}