Skip to content

Instantly share code, notes, and snippets.

@jenya239
Last active August 6, 2021 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jenya239/94e9d67c969923ab5c250b046fed0c3c to your computer and use it in GitHub Desktop.
Save jenya239/94e9d67c969923ab5c250b046fed0c3c to your computer and use it in GitHub Desktop.
import React, { Context, useContext } from 'react'
export interface IEntityProviderProps<EntityType> {
children: React.ReactNode
context: Context<ValueType<EntityType>>
entity: EntityType | undefined
}
type ValueType<EntityType> = { initialized: true; entity: EntityType } | { initialized: false }
export const createContext = <EntityType extends unknown>(): Context<ValueType<EntityType>> =>
React.createContext<ValueType<EntityType>>({ initialized: false })
export function EntityProvider<EntityType extends unknown>({
context,
children,
entity,
}: IEntityProviderProps<EntityType>): JSX.Element {
return (
<context.Provider value={entity ? { initialized: true, entity } : { initialized: false }}>
{children}
</context.Provider>
)
}
export const useEntity = <EntityType extends unknown>(
Context: Context<ValueType<EntityType>>,
name: string
) => {
const context = useContext(Context)
if (context === undefined) {
throw new Error(`useContext must be used within a ${name}Provider`)
}
return context.initialized ? context.entity : undefined
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment