From 436fe821b81675f1aa6d03c30dc3a3604f8d2781 Mon Sep 17 00:00:00 2001 From: Jamie Kyle Date: Wed, 1 May 2019 12:17:21 -0700 Subject: init commit --- src/unstated-next.tsx | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/unstated-next.tsx (limited to 'src') diff --git a/src/unstated-next.tsx b/src/unstated-next.tsx new file mode 100644 index 0000000..b19f8ba --- /dev/null +++ b/src/unstated-next.tsx @@ -0,0 +1,33 @@ +import React from "react" + +interface ContainerProviderProps { + children: React.ReactNode +} + +interface Container { + Provider: React.ComponentType + useContainer: () => Value +} + +export function createContainer(useHook: () => Value): Container { + let Context = React.createContext(null) + + function Provider(props: ContainerProviderProps) { + let value = useHook() + return {props.children} + } + + function useContainer(): Value { + let value = React.useContext(Context) + if (value === null) { + throw new Error("Component must be wrapped with ") + } + return value + } + + return { Provider, useContainer } +} + +export function useContainer(container: Container): Value { + return container.useContainer() +} -- cgit v1.2.3