-
-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathcreate-context-store.tsx
116 lines (101 loc) · 2.35 KB
/
create-context-store.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import { Action, action, createContextStore } from 'easy-peasy';
import * as React from 'react';
interface StoreModel {
count: number;
inc: Action<StoreModel>;
}
interface RuntimeModel {
count: number;
}
interface Injections {
foo: string;
}
const Counter = createContextStore<StoreModel>({
count: 0,
inc: action((state) => {
state.count += 1;
}),
});
const CounterWithCustomRuntimeModel = createContextStore<
StoreModel,
any,
RuntimeModel
>((data) => ({
count: data ? data.count + 1 : 0,
inc: action((state) => {
state.count += 1;
}),
}));
const CounterWithInjections = createContextStore<StoreModel, Injections>(
{
count: 0,
inc: action((state) => {
state.count += 1;
}),
},
{
injections: {
foo: 'bar',
},
},
);
function CountDisplay() {
const count = Counter.useStoreState((state) => state.count);
const inc = Counter.useStoreActions((actions) => actions.inc);
return (
<>
<div>{count + 1}</div>
<button onClick={() => inc()} type="button">
+
</button>
</>
);
}
function CountDisplayUseStore() {
const store = Counter.useStore();
return (
<>
<div>{store.getState().count + 1}</div>
<button onClick={() => store.getActions().inc()} type="button">
+
</button>
</>
);
}
function TestDispatch() {
const dispatch = Counter.useStoreDispatch();
dispatch({
type: 'FOO',
payload: 'bar',
});
return null;
}
<CounterWithInjections.Provider injections={{ foo: 'baz' }}>
<CountDisplay />
</CounterWithInjections.Provider>;
<CounterWithCustomRuntimeModel.Provider runtimeModel={{ count: 1 }}>
<CountDisplay />
</CounterWithCustomRuntimeModel.Provider>;
<CounterWithCustomRuntimeModel.Provider
// @ts-expect-error
runtimeModel={{ count: 'foo' }}
>
<CountDisplay />
</CounterWithCustomRuntimeModel.Provider>;
<CounterWithInjections.Provider
injections={(previousInjections) => ({ foo: 'baz' + previousInjections.foo })}
>
<CountDisplay />
</CounterWithInjections.Provider>;
<CounterWithInjections.Provider
// @ts-expect-error
injections={{ foo: 1 }}
>
<CountDisplay />
</CounterWithInjections.Provider>;
<CounterWithInjections.Provider
// This will default to the StoreModel as we didn't specify a model
runtimeModel={{ count: 1, inc: action(() => {}) }}
>
<CountDisplay />
</CounterWithInjections.Provider>;