Last active
August 6, 2021 08:21
-
-
Save jenya239/94e9d67c969923ab5c250b046fed0c3c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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