(options: CreateContextOptions<T> = {})
| 17 | } |
| 18 | |
| 19 | export function createContext<T>(options: CreateContextOptions<T> = {}) { |
| 20 | const { |
| 21 | name, |
| 22 | strict = true, |
| 23 | hookName = 'useContext', |
| 24 | providerName = 'Provider', |
| 25 | errorMessage, |
| 26 | defaultValue, |
| 27 | } = options |
| 28 | |
| 29 | const Context = createReactContext<T | undefined>(defaultValue) |
| 30 | |
| 31 | Context.displayName = name |
| 32 | |
| 33 | function useContext() { |
| 34 | const context = useReactContext(Context) |
| 35 | |
| 36 | if (!context && strict) { |
| 37 | const error = new Error(errorMessage ?? getErrorMessage(hookName, providerName)) |
| 38 | error.name = 'ContextError' |
| 39 | if (hasProp(Error, 'captureStackTrace') && isFunction(Error.captureStackTrace)) { |
| 40 | Error.captureStackTrace(error, useContext) |
| 41 | } |
| 42 | throw error |
| 43 | } |
| 44 | |
| 45 | return context |
| 46 | } |
| 47 | |
| 48 | return [Context.Provider, useContext, Context] as CreateContextReturn<T> |
| 49 | } |
no outgoing calls
no test coverage detected