From 041cf56036086ebf7593b7e950063968015eeb2e Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Fri, 10 Sep 2021 17:09:09 +0200 Subject: [PATCH] version-bridge: added createVersionedContext Signed-off-by: Patrik Oldsberg --- .../src/lib/VersionedContext.ts | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/version-bridge/src/lib/VersionedContext.ts b/packages/version-bridge/src/lib/VersionedContext.ts index 62aed0d9ed..bd80365c2f 100644 --- a/packages/version-bridge/src/lib/VersionedContext.ts +++ b/packages/version-bridge/src/lib/VersionedContext.ts @@ -15,13 +15,39 @@ */ import { createContext, useContext, Context } from 'react'; -import { getGlobalSingleton } from './globalObject'; +import { getGlobalSingleton, getOrCreateGlobalSingleton } from './globalObject'; import { createVersionedValueMap, VersionedValue } from './VersionedValue'; +/** + * Get the existing or create a new versioned React context that's + * stored inside a global singleton. + * + * @param key - A key that uniquely identifies the context. + * @example + * + * ```ts + * const MyContext = createVersionedContext<{ 1: string }>('my-context'); + * + * const MyContextProvider = ({children}) => ( + * + * {children} + * + * ) + * ``` + */ +export function createVersionedContext< + Versions extends { [version in number]: any }, +>(key: string): Context | undefined> { + return getOrCreateGlobalSingleton(key, () => + createContext | undefined>(undefined), + ); +} + /** * A hook that simplifies the consumption of a versioned contexts that's * stored inside a global singleton. * + * @param key - A key that uniquely identifies the context. * @example * * ```ts @@ -48,6 +74,7 @@ export function useVersionedContext< * Creates a helper for writing tests towards multiple different * combinations of versions provided from a context. * + * @param key - A key that uniquely identifies the context. * @example * * ```ts