Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 142x 142x 142x 1745x 1745x 1745x 142x | import React from "react"; export interface CreateContextOptions { /** * If `true`, React will throw if context is `null` or `undefined` * In some cases, you might want to support nested context, so you can set it to `false` */ strict?: boolean; /** * Error message to throw if the context is `undefined` */ errorMessage?: string; /** * The display name of the context */ name?: string; } type CreateContextReturn<T> = [React.Provider<T>, () => T, React.Context<T>]; /** * Creates a named context, provider, and hook. * * @param options create context options */ export function createContextProvider<ContextType>( options: CreateContextOptions, ): CreateContextReturn<ContextType> { const { errorMessage = "useContext: `context` is undefined. Seems you forgot to wrap component within the Provider", name, } = options; const Context = React.createContext<ContextType | undefined>(undefined); Context.displayName = name; function useContext<T extends ContextType = ContextType>() { const context = React.useContext(Context); Iif (!context) { const error = new Error(errorMessage); error.name = "ContextError"; Error.captureStackTrace?.(error, useContext); throw error; } return context as T; } return [Context.Provider, useContext, Context] as CreateContextReturn<ContextType>; } |