-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppBare.tsx
75 lines (62 loc) · 1.59 KB
/
AppBare.tsx
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import React, { createContext, useContext } from "react";
import { useCounter } from "./useCounter";
interface ContainerProviderProps<State = void> {
initialState?: State;
children: React.ReactNode;
}
interface Container<Value, State = void> {
Provider: React.ComponentType<ContainerProviderProps<State>>;
useContainer: () => Value;
}
function createContainer<Value, State = void>(
useHook: (initialState?: State) => Value
): Container<Value, State> {
const Context = createContext<Value | null>(null);
return {
Provider({
initialState,
children
}: {
initialState?: State;
children: React.ReactNode;
}) {
const value = useHook(initialState);
return <Context.Provider value={value}>{children}</Context.Provider>;
},
useContainer() {
const container = useContext(Context);
if (!container) {
throw new Error();
}
return container;
}
};
}
const Counter = createContainer(useCounter);
function CounterDisplay() {
const { count, decrement, increment } = Counter.useContainer();
return (
<div>
<button onClick={decrement}>-</button>
<span>{count}</span>
<button onClick={increment}>+</button>
</div>
);
}
export function AppBare() {
return (
<Counter.Provider>
<CounterDisplay />
<Counter.Provider initialState={1}>
<div>
<div>
<CounterDisplay />
</div>
</div>
</Counter.Provider>
<Counter.Provider initialState={2}>
<CounterDisplay />
</Counter.Provider>
</Counter.Provider>
);
}