kiss-for-react 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +699 -156
  2. package/lib/cjs/ClassPersistor.js +177 -112
  3. package/lib/cjs/Esserializer/DeserializationOptions.js +4 -4
  4. package/lib/cjs/Esserializer/SerializeOptions.js +4 -4
  5. package/lib/cjs/Esserializer/builtins.js +258 -0
  6. package/lib/cjs/Esserializer/constant.js +39 -131
  7. package/lib/cjs/Esserializer/deserializer.js +226 -313
  8. package/lib/cjs/Esserializer/general.js +91 -39
  9. package/lib/cjs/Esserializer/index.js +47 -43
  10. package/lib/cjs/Esserializer/serializer.js +168 -133
  11. package/lib/cjs/Evt.js +132 -0
  12. package/lib/cjs/Hooks.js +1472 -969
  13. package/lib/cjs/KissAction.js +4635 -1333
  14. package/lib/cjs/LoadPages.js +336 -0
  15. package/lib/cjs/Persistor.js +189 -120
  16. package/lib/cjs/ProcessPersistence.js +579 -262
  17. package/lib/cjs/Store.js +4278 -1534
  18. package/lib/cjs/StoreException.js +162 -75
  19. package/lib/cjs/StoreProvider.js +88 -0
  20. package/lib/cjs/UserException.js +212 -218
  21. package/lib/cjs/Wait.js +309 -309
  22. package/lib/cjs/index.js +69 -42
  23. package/lib/cjs/server.js +54 -0
  24. package/lib/cjs/types/ClassPersistor.d.ts +143 -112
  25. package/lib/cjs/types/ClassPersistor.d.ts.map +1 -1
  26. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +13 -6
  27. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  28. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +11 -5
  29. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  30. package/lib/cjs/types/Esserializer/builtins.d.ts +36 -0
  31. package/lib/cjs/types/Esserializer/builtins.d.ts.map +1 -0
  32. package/lib/cjs/types/Esserializer/constant.d.ts +25 -49
  33. package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -1
  34. package/lib/cjs/types/Esserializer/deserializer.d.ts +27 -17
  35. package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
  36. package/lib/cjs/types/Esserializer/general.d.ts +28 -4
  37. package/lib/cjs/types/Esserializer/general.d.ts.map +1 -1
  38. package/lib/cjs/types/Esserializer/index.d.ts +33 -29
  39. package/lib/cjs/types/Esserializer/index.d.ts.map +1 -1
  40. package/lib/cjs/types/Esserializer/serializer.d.ts +14 -3
  41. package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -1
  42. package/lib/cjs/types/Evt.d.ts +124 -0
  43. package/lib/cjs/types/Evt.d.ts.map +1 -0
  44. package/lib/cjs/types/Hooks.d.ts +1174 -837
  45. package/lib/cjs/types/Hooks.d.ts.map +1 -1
  46. package/lib/cjs/types/KissAction.d.ts +5199 -1398
  47. package/lib/cjs/types/KissAction.d.ts.map +1 -1
  48. package/lib/cjs/types/LoadPages.d.ts +287 -0
  49. package/lib/cjs/types/LoadPages.d.ts.map +1 -0
  50. package/lib/cjs/types/Persistor.d.ts +187 -118
  51. package/lib/cjs/types/Persistor.d.ts.map +1 -1
  52. package/lib/cjs/types/ProcessPersistence.d.ts +197 -99
  53. package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -1
  54. package/lib/cjs/types/Store.d.ts +2253 -1042
  55. package/lib/cjs/types/Store.d.ts.map +1 -1
  56. package/lib/cjs/types/StoreException.d.ts +97 -28
  57. package/lib/cjs/types/StoreException.d.ts.map +1 -1
  58. package/lib/cjs/types/StoreProvider.d.ts +80 -0
  59. package/lib/cjs/types/StoreProvider.d.ts.map +1 -0
  60. package/lib/cjs/types/UserException.d.ts +178 -169
  61. package/lib/cjs/types/UserException.d.ts.map +1 -1
  62. package/lib/cjs/types/index.d.ts +12 -9
  63. package/lib/cjs/types/index.d.ts.map +1 -1
  64. package/lib/cjs/types/server.d.ts +12 -0
  65. package/lib/cjs/types/server.d.ts.map +1 -0
  66. package/lib/cjs/types/utils.d.ts +15 -1
  67. package/lib/cjs/types/utils.d.ts.map +1 -1
  68. package/lib/cjs/utils.js +45 -7
  69. package/lib/esm/ClassPersistor.mjs +177 -0
  70. package/lib/esm/Esserializer/{DeserializationOptions.js → DeserializationOptions.mjs} +3 -3
  71. package/lib/esm/Esserializer/{SerializeOptions.js → SerializeOptions.mjs} +3 -3
  72. package/lib/esm/Esserializer/builtins.mjs +254 -0
  73. package/lib/esm/Esserializer/constant.mjs +28 -0
  74. package/lib/esm/Esserializer/deserializer.mjs +221 -0
  75. package/lib/esm/Esserializer/general.mjs +81 -0
  76. package/lib/esm/Esserializer/index.mjs +43 -0
  77. package/lib/esm/Esserializer/serializer.mjs +164 -0
  78. package/lib/esm/Evt.mjs +151 -0
  79. package/lib/esm/Hooks.mjs +1446 -0
  80. package/lib/esm/KissAction.mjs +4689 -0
  81. package/lib/esm/LoadPages.mjs +340 -0
  82. package/lib/esm/Persistor.mjs +180 -0
  83. package/lib/esm/ProcessPersistence.mjs +581 -0
  84. package/lib/esm/Store.mjs +4400 -0
  85. package/lib/esm/StoreException.mjs +153 -0
  86. package/lib/esm/StoreProvider.mjs +80 -0
  87. package/lib/esm/{UserException.js → UserException.mjs} +240 -246
  88. package/lib/esm/{Wait.js → Wait.mjs} +309 -309
  89. package/lib/esm/index.mjs +12 -9
  90. package/lib/esm/server.mjs +23 -0
  91. package/lib/esm/types/ClassPersistor.d.ts +143 -112
  92. package/lib/esm/types/ClassPersistor.d.ts.map +1 -1
  93. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +13 -6
  94. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  95. package/lib/esm/types/Esserializer/SerializeOptions.d.ts +11 -5
  96. package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  97. package/lib/esm/types/Esserializer/builtins.d.ts +36 -0
  98. package/lib/esm/types/Esserializer/builtins.d.ts.map +1 -0
  99. package/lib/esm/types/Esserializer/constant.d.ts +25 -49
  100. package/lib/esm/types/Esserializer/constant.d.ts.map +1 -1
  101. package/lib/esm/types/Esserializer/deserializer.d.ts +27 -17
  102. package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
  103. package/lib/esm/types/Esserializer/general.d.ts +28 -4
  104. package/lib/esm/types/Esserializer/general.d.ts.map +1 -1
  105. package/lib/esm/types/Esserializer/index.d.ts +33 -29
  106. package/lib/esm/types/Esserializer/index.d.ts.map +1 -1
  107. package/lib/esm/types/Esserializer/serializer.d.ts +14 -3
  108. package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -1
  109. package/lib/esm/types/Evt.d.ts +124 -0
  110. package/lib/esm/types/Evt.d.ts.map +1 -0
  111. package/lib/esm/types/Hooks.d.ts +1174 -837
  112. package/lib/esm/types/Hooks.d.ts.map +1 -1
  113. package/lib/esm/types/KissAction.d.ts +5199 -1398
  114. package/lib/esm/types/KissAction.d.ts.map +1 -1
  115. package/lib/esm/types/LoadPages.d.ts +287 -0
  116. package/lib/esm/types/LoadPages.d.ts.map +1 -0
  117. package/lib/esm/types/Persistor.d.ts +187 -118
  118. package/lib/esm/types/Persistor.d.ts.map +1 -1
  119. package/lib/esm/types/ProcessPersistence.d.ts +197 -99
  120. package/lib/esm/types/ProcessPersistence.d.ts.map +1 -1
  121. package/lib/esm/types/Store.d.ts +2253 -1042
  122. package/lib/esm/types/Store.d.ts.map +1 -1
  123. package/lib/esm/types/StoreException.d.ts +97 -28
  124. package/lib/esm/types/StoreException.d.ts.map +1 -1
  125. package/lib/esm/types/StoreProvider.d.ts +80 -0
  126. package/lib/esm/types/StoreProvider.d.ts.map +1 -0
  127. package/lib/esm/types/UserException.d.ts +178 -169
  128. package/lib/esm/types/UserException.d.ts.map +1 -1
  129. package/lib/esm/types/index.d.ts +12 -9
  130. package/lib/esm/types/index.d.ts.map +1 -1
  131. package/lib/esm/types/server.d.ts +12 -0
  132. package/lib/esm/types/server.d.ts.map +1 -0
  133. package/lib/esm/types/utils.d.ts +15 -1
  134. package/lib/esm/types/utils.d.ts.map +1 -1
  135. package/lib/esm/utils.mjs +38 -0
  136. package/package.json +54 -30
  137. package/lib/cjs/UnmodifiableSetView.js +0 -53
  138. package/lib/cjs/types/UnmodifiableSetView.d.ts +0 -24
  139. package/lib/cjs/types/UnmodifiableSetView.d.ts.map +0 -1
  140. package/lib/esm/ClassPersistor.js +0 -112
  141. package/lib/esm/Esserializer/constant.js +0 -81
  142. package/lib/esm/Esserializer/deserializer.js +0 -307
  143. package/lib/esm/Esserializer/general.js +0 -34
  144. package/lib/esm/Esserializer/index.js +0 -39
  145. package/lib/esm/Esserializer/serializer.js +0 -130
  146. package/lib/esm/Hooks.js +0 -955
  147. package/lib/esm/KissAction.js +0 -1459
  148. package/lib/esm/Persistor.js +0 -113
  149. package/lib/esm/ProcessPersistence.js +0 -262
  150. package/lib/esm/Store.js +0 -1606
  151. package/lib/esm/StoreException.js +0 -69
  152. package/lib/esm/UnmodifiableSetView.js +0 -50
  153. package/lib/esm/types/UnmodifiableSetView.d.ts +0 -24
  154. package/lib/esm/types/UnmodifiableSetView.d.ts.map +0 -1
  155. package/lib/esm/utils.js +0 -3
@@ -1,838 +1,1175 @@
1
- import { UserException } from './UserException';
2
- import { Store } from "./Store";
3
- import { KissAction, ActionStatus } from './KissAction';
4
- /**
5
- * Returns a part of the store state:
6
- *
7
- * ```ts
8
- * const name = useSelect((state: State) => state.user.name);
9
- * ```
10
- *
11
- * The component will rebuild only when the `name` changes, ignoring the
12
- * change in other parts of the state.
13
- *
14
- * Note: You can use `useSelect` and `useSelector` interchangeably.
15
- * Prefer `useSelect` because it's shorter.
16
- */
17
- export declare function useSelect<St, T>(selector: (state: St) => T): T;
18
- /**
19
- * Returns a part of the store state:
20
- *
21
- * ```ts
22
- * const name = useSelector((state: State) => state.user.name);
23
- * ```
24
- *
25
- * The component will rebuild only when the `name` changes, ignoring the
26
- * change in other parts of the state.
27
- *
28
- * Note: You can use `useSelect` and `useSelector` interchangeably.
29
- * Prefer `useSelect` because it's shorter.
30
- */
31
- export declare function useSelector<St, T>(selector: (state: St) => T): T;
32
- /**
33
- * Returns the whole store state:
34
- *
35
- * ```ts
36
- * const state = useAllState<State>();
37
- * const name = state.user.name;
38
- * ```
39
- *
40
- * While that's convenient, the above code will rebuild the component for all state changes,
41
- * no matter if the name changed or not. For this reason, prefer `useSelector`:
42
- *
43
- * ```ts
44
- * const name = useSelector((state: State) => state.user.name);
45
- * ```
46
- *
47
- * Now it will rebuild only when the name changes.
48
- */
49
- export declare function useAllState<St>(): St;
50
- /**
51
- * You can get the store to use all dispatch and wait methods:
52
- *
53
- * - `dispatch` - Dispatches the action to the Redux store, to potentially change the state.
54
- * - `dispatchAndWait` - Dispatches an action and returns a promise that resolves when the action finishes.
55
- * - `dispatchSync` - Same as the regular dispatch, except it throws an error if the action is ASYNC.
56
- * - `waitCondition` - Waits until the state is in a given condition.
57
- * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
58
- * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
59
- * - `waitActionType` - Waits until an action of a given type is NOT in progress.
60
- * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
61
- * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
62
- *
63
- * Example:
64
- *
65
- * ```js
66
- * const store = useStore();
67
- * store.dispatch(new MyAction());
68
- * await store.dispatchAndWait(new MyAction());
69
- * store.dispatchSync(new MyAction());
70
- * await waitCondition((state) => state.user.name === "Bill");
71
- * await waitAllActionTypes(['BuyAction', 'SellAction']);
72
- * ```
73
- *
74
- * IMPORTANT:
75
- * The store `state` and other store methods are NOT available when you get the store with `useStore`.
76
- * - To get the state: `useSelect`
77
- * - To wait for actions: `useIsWaiting`
78
- * - To deal with exceptions: `useIsFailed`, `useExceptionFor` and `clearExceptionFor`
79
- *
80
- * See also:
81
- * - `useDispatch()` - Hook equivalent to `useStore().dispatch`
82
- * - `useDispatchAndWait` - Hook equivalent to `useStore().dispatchAndWait`
83
- * - `useDispatchSync` - Hook equivalent to `useStore().dispatchSync`
84
- */
85
- export declare function useStore(): StoreDispatchers<any>;
86
- /**
87
- * @deprecated Use `useDispatch`. Note you also have `useDispatchAndWait` and `useDispatchSync`.
88
- */
89
- export declare function useDispatcher(): (action: KissAction<any>) => void;
90
- /**
91
- * Dispatches the action to the Redux store, to potentially change the state:
92
- *
93
- * ```ts
94
- * const dispatch = useDispatch();
95
- * dispatch(MyAction());
96
- * ```
97
- *
98
- * This also works:
99
- *
100
- * ```ts
101
- * const store = useStore();
102
- * dispatch(MyAction());
103
- * ```
104
- *
105
- * See also:
106
- * - `dispatchAll` which dispatches all given actions in parallel.
107
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
108
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
109
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
110
- */
111
- export declare function useDispatch(): (action: KissAction<any>) => void;
112
- /**
113
- * Dispatches an action and returns a promise that resolves when the action finishes.
114
- * While the state change from the action's reducer will have been applied when the promise
115
- * resolves, other independent processes that the action may have started may still be in
116
- * progress.
117
- *
118
- * Usage:
119
- * ```ts
120
- * const dispatchAndWait = useDispatchAndWait();
121
- * await dispatchAndWait(new MyAction())`.
122
- * ```
123
- *
124
- * See also:
125
- * - `dispatch` which dispatches both sync and async actions.
126
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
127
- * - `dispatchAll` which dispatches all given actions in parallel.
128
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
129
- */
130
- export declare function useDispatchAndWait(): (action: KissAction<any>) => Promise<ActionStatus>;
131
- /**
132
- * Dispatches all given actions in parallel, applying their reducers, and possibly changing
133
- * the store state. The actions may be sync or async. It returns a Promise that resolves when
134
- * ALL actions finish.
135
- *
136
- * ```ts
137
- * const dispatchAndWaitAll = useDispatchAndWaitAll();
138
- * await dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
139
- * ```
140
- *
141
- * Note: While the state change from the action's reducers will have been applied when the
142
- * Promise resolves, other independent processes that the action may have started may still
143
- * be in progress.
144
- *
145
- * See also:
146
- * - `dispatch` which dispatches both sync and async actions.
147
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
148
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
149
- * - `dispatchAll` which dispatches all given actions in parallel.
150
- */
151
- export declare function useDispatchAndWaitAll(): (action: KissAction<any>[]) => Promise<KissAction<any>[]>;
152
- /**
153
- * Dispatches all given actions in parallel, applying their reducer, and possibly changing
154
- * the store state.
155
- *
156
- * ```ts
157
- * const dispatchAll = useDispatchAll();
158
- * dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
159
- * ```
160
- *
161
- * See also:
162
- * - `dispatch` which dispatches both sync and async actions.
163
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
164
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
165
- * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
166
- */
167
- export declare function useDispatchAll(): (action: KissAction<any>[]) => KissAction<any>[];
168
- /**
169
- * Dispatches the given action to the Redux store, to potentially change the state.
170
- *
171
- * This is exactly the same as the regular `dispatch`, except for the fact it
172
- * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
173
- * if any of its `reduce()` or `before()` methods return a Promise.
174
- *
175
- * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
176
- * action is SYNC, which means the state gets changed right after the dispatch call.
177
- *
178
- * See also:
179
- * - `dispatch` which dispatches both sync and async actions.
180
- * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
181
- * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
182
- * - `dispatchAll` which dispatches all given actions in parallel.
183
- */
184
- export declare function useDispatchSync(): (action: KissAction<any>) => void;
185
- /**
186
- * You can use `isWaiting` and pass it an action `type`:
187
- * - It returns true if an ASYNC action of the specific type is currently being processed.
188
- * - It returns false if an ASYNC action of the specific type is NOT currently being processed.
189
- * - This is only useful for ASYNC actions, since it always returns `false` when the action is SYNC.
190
- *
191
- * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
192
- *
193
- * ```ts
194
- * const isWaiting = useIsWaiting(MyAction);
195
- * if (isWaiting) { // Show a spinner }
196
- * ```
197
- */
198
- export declare function useIsWaiting(type: {
199
- new (...args: any[]): KissAction<any>;
200
- }): boolean;
201
- /**
202
- * Returns true if the given action `type` failed with an `UserException`.
203
- * Note: This method uses the EXACT action type. Subtypes are not considered.
204
- */
205
- export declare function useIsFailed(type: {
206
- new (...args: any[]): KissAction<any>;
207
- }): boolean;
208
- /**
209
- * Returns the `UserException` of the `type` that failed.
210
- * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
211
- */
212
- export declare function useExceptionFor(type: {
213
- new (...args: any[]): KissAction<any>;
214
- }): UserException | null;
215
- /**
216
- * Removes the exact given action `type` from the list of action types that failed.
217
- * Note it clears the EXACT given type. Subtypes are not considered.
218
- *
219
- * Even if you never call this method explicitly, just dispatching an action already clears that action type
220
- * from the list of failing action types. But you can call this method explicitly if you want to clear the
221
- * action type before it's used again.
222
- *
223
- * Usage:
224
- * ```ts
225
- * const clearExceptionFor = useClearExceptionFor();
226
- * clearExceptionFor(MyAction);
227
- * clearExceptionFor(AnotherAction);
228
- * ```
229
- */
230
- export declare function useClearExceptionFor(): (type: {
231
- new (...args: any[]): KissAction<any>;
232
- }) => void;
233
- /**
234
- * Helper class that allows us to write:
235
- *
236
- * ```js
237
- * const store = useStore();
238
- * store.dispatch(new MyAction());
239
- * store.dispatchSync(new MyAction());
240
- * await store.dispatchAndWait(new MyAction());
241
- * ```
242
- */
243
- declare class StoreDispatchers<St> {
244
- store: Store<St>;
245
- constructor(store: Store<St>);
246
- /**
247
- * Dispatches the action to the Redux store, to potentially change the state.
248
- */
249
- dispatch(action: KissAction<any>): void;
250
- /**
251
- * Dispatches an action and returns a promise that resolves when the action finishes.
252
- * While the state change from the action's reducer will have been applied when the promise
253
- * resolves, other independent processes that the action may have started may still be in
254
- * progress.
255
- *
256
- * Usage: `await store.dispatchAndWait(new MyAction())`.
257
- */
258
- dispatchAndWait(action: KissAction<any>): Promise<ActionStatus>;
259
- /**
260
- * Dispatches the given action to the Redux store, to potentially change the state.
261
- *
262
- * This is exactly the same as the regular `dispatch`, except for the fact it
263
- * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
264
- * if any of its `reduce()` or `before()` methods return a Promise.
265
- *
266
- * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
267
- * action is SYNC, which means the state gets changed right after the dispatch call.
268
- */
269
- dispatchSync(action: KissAction<any>): void;
270
- /**
271
- * Returns a promise which will resolve when the given state `condition` is true.
272
- * If the condition is already true when the method is called, the promise resolves immediately.
273
- *
274
- * You may also provide a `timeoutMillis`, which by default is 10 minutes. If you want, you
275
- * can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
276
- * To disable the timeout, make it 0 or -1.
277
- *
278
- * This method is useful in tests, and it returns the action which changed
279
- * the store state into the condition, in case you need it:
280
- *
281
- * ```typescript
282
- * let action = await store.waitCondition((state) => state.name == "Bill");
283
- * expect(action instanceof ChangeNameAction).toBe(true);
284
- *
285
- * This method is also eventually useful in production code, in which case you
286
- * should avoid waiting for conditions that may take a very long time to complete,
287
- * as checking the condition is an overhead to every state change.
288
- *
289
- * Examples:
290
- *
291
- * // Dispatches an actions that changes the state, then await for the state change:
292
- * expect(store.state.name, 'John')
293
- * dispatch(new ChangeNameAction("Bill"));
294
- * let action = await store.waitCondition((state) => state.name == "Bill");
295
- * expect(action instanceof ChangeNameAction).toBe(true);
296
- * expect(store.state.name, 'Bill');
297
- *
298
- * // Dispatches actions and wait until no actions are in progress.
299
- * dispatch(new BuyAction('IBM'));
300
- * dispatch(new BuyAction('TSLA'));
301
- * await waitAllActions([]);
302
- * expect(state.stocks, ['IBM', 'TSLA']);
303
- *
304
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
305
- * expect(store.state.portfolio, ['TSLA']);
306
- * dispatch(new BuyAction('IBM'));
307
- * dispatch(new SellAction('TSLA'));
308
- * await store.waitAllActionTypes([BuyAction, SellAction]);
309
- * expect(store.state.portfolio, ['IBM']);
310
- *
311
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
312
- * dispatch(new BuyAction('IBM'));
313
- * dispatch(new BuyAction('TSLA'));
314
- * await store.waitAllActions([]);
315
- * expect(store.state.portfolio.includes('IBM', 'TSLA')).toBe(false);
316
- *
317
- * // Dispatches two actions in PARALLEL and wait for them:
318
- * let action1 = new BuyAction('IBM');
319
- * let action2 = new SellAction('TSLA');
320
- * dispatch(action1);
321
- * dispatch(action2);
322
- * await store.waitAllActions([action1, action2]);
323
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
324
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
325
- *
326
- * // Dispatches two actions in SERIES and wait for them:
327
- * await dispatchAndWait(new BuyAction('IBM'));
328
- * await dispatchAndWait(new SellAction('TSLA'));
329
- * expect(store.state.portfolio.includes('IBM', 'TSLA')).toBe(false);
330
- *
331
- * // Wait until some action of a given type is dispatched.
332
- * dispatch(new DoALotOfStuffAction());
333
- * let action = store.waitActionType(ChangeNameAction);
334
- * expect(action instanceof ChangeNameAction).toBe(true);
335
- * expect(action.status.isCompletedOk).toBe(true);
336
- * expect(store.state.name, 'Bill');
337
- *
338
- * // Wait until some action of the given types is dispatched.
339
- * dispatch(new ProcessStocksAction());
340
- * let action = store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
341
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
342
- *
343
- * See also:
344
- * `waitCondition` - Waits until the state is in a given condition.
345
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
346
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
347
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
348
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
349
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
350
- */
351
- waitCondition(condition: (state: St) => boolean, timeoutMillis?: number | null): Promise<KissAction<St> | null>;
352
- /**
353
- * Returns a Promise that resolves when some actions meet the given `condition`.
354
- *
355
- * If `completeImmediately` is false (the default), this method will throw an error if the
356
- * condition was already true when the method was called. Otherwise, the promise will complete
357
- * immediately and throw no error.
358
- *
359
- * The `condition` is a function that takes the set of actions "in progress", as well as an
360
- * action that just entered the set (by being dispatched) or left the set (by finishing
361
- * dispatching). The function should return `true` when the condition is met, and `false`
362
- * otherwise. For example:
363
- *
364
- * ```ts
365
- * let action = await store.waitActionCondition((actionsInProgress, triggerAction) => { ... });
366
- * ```
367
- *
368
- * Important: Your condition function should NOT modify the set of actions.
369
- *
370
- * You get back the set of the actions being dispatched that met the condition, as well as
371
- * the action that triggered the condition by being added or removed from the set.
372
- *
373
- * Note: The condition is only checked when some action is dispatched or finishes dispatching.
374
- * It's not checked every time action statuses change.
375
- *
376
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
377
- * To disable the timeout, make it 0 or -1.
378
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
379
- *
380
- * Examples:
381
- *
382
- * ```ts
383
- * // Dispatches an actions that changes the state, then await for the state change:
384
- * expect(store.state.name).toBe('John');
385
- * dispatch(new ChangeNameAction("Bill"));
386
- * let action = await store.waitCondition((state) => state.name == "Bill");
387
- * expect(action instanceof ChangeNameAction).toBe(true);
388
- * expect(store.state.name).toBe('Bill');
389
- *
390
- * // Dispatches actions and wait until no actions are in progress.
391
- * dispatch(new BuyAction('IBM'));
392
- * dispatch(new BuyAction('TSLA'));
393
- * await waitAllActions();
394
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
395
- *
396
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
397
- * expect(store.state.portfolio).toEqual(['TSLA']);
398
- * dispatch(new BuyAction('IBM'));
399
- * dispatch(new SellAction('TSLA'));
400
- * await store.waitAllActionTypes([BuyAction, SellAction]);
401
- * expect(store.state.portfolio).toEqual(['IBM']);
402
- *
403
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
404
- * dispatch(new BuyAction('IBM'));
405
- * dispatch(new BuyAction('TSLA'));
406
- * await store.waitAllActions();
407
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
408
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
409
- *
410
- * // Dispatches two actions in PARALLEL and wait for them:
411
- * let action1 = new BuyAction('IBM');
412
- * let action2 = new SellAction('TSLA');
413
- * dispatch(action1);
414
- * dispatch(action2);
415
- * await store.waitAllActions([action1, action2]);
416
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
417
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
418
- *
419
- * // Dispatches two actions in SERIES and wait for them:
420
- * await dispatchAndWait(new BuyAction('IBM'));
421
- * await dispatchAndWait(new SellAction('TSLA'));
422
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
423
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
424
- *
425
- * // Wait until some action of a given type is dispatched.
426
- * dispatch(new DoALotOfStuffAction());
427
- * let action = await store.waitActionType(ChangeNameAction);
428
- * expect(action instanceof ChangeNameAction).toBe(true);
429
- * expect(action.status.isCompletedOk).toBe(true);
430
- * expect(store.state.name).toBe('Bill');
431
- *
432
- * // Wait until some action of the given types is dispatched.
433
- * dispatch(new ProcessStocksAction());
434
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
435
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
436
- * ```
437
- *
438
- * See also:
439
- * `waitCondition` - Waits until the state is in a given condition.
440
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
441
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
442
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
443
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
444
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
445
- *
446
- * You should only use this method in tests.
447
- */
448
- waitActionCondition(condition: (actions: Set<KissAction<St>>, triggerAction: KissAction<St> | null) => boolean, { completeImmediately, timeoutMillis, }?: {
449
- completeImmediately?: boolean;
450
- timeoutMillis?: number | null;
451
- }): Promise<{
452
- actions: Set<KissAction<St>>;
453
- triggerAction: KissAction<St> | null;
454
- }>;
455
- /**
456
- * Returns a promise that resolves when ALL given actions finished dispatching.
457
- *
458
- * If `completeImmediately` is false (the default), this method will throw an error if none
459
- * of the given actions are in progress when the method is called. Otherwise, the promise will
460
- * complete immediately and throw no error.
461
- *
462
- * However, if you don't provide any actions (empty list or `null`), the promise will complete
463
- * when ALL current actions in progress finish dispatching. In other words, when no actions are
464
- * currently in progress. In this case, if [completeImmediately] is `false`, the method will
465
- * throw an error if no actions are in progress when the method is called.
466
- *
467
- * Note: Waiting until no actions are in progress should only be done in test, never in
468
- * production, as it's very easy to create a deadlock. However, waiting for specific actions to
469
- * finish is safe in production, as long as you're waiting for actions you just dispatched.
470
- *
471
- * You may also provide a [timeoutMillis], which by default is 10 minutes.
472
- * To disable the timeout, make it 0 or -1.
473
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
474
- *
475
- * Examples:
476
- *
477
- * ```ts
478
- * // Dispatches an actions that changes the state, then await for the state change:
479
- * expect(store.state.name).toBe('John');
480
- * dispatch(new ChangeNameAction("Bill"));
481
- * let action = await store.waitCondition((state) => state.name == "Bill");
482
- * expect(action instanceof ChangeNameAction).toBe(true);
483
- * expect(store.state.name).toBe('Bill');
484
- *
485
- * // Dispatches actions and wait until no actions are in progress.
486
- * dispatch(new BuyAction('IBM'));
487
- * dispatch(new BuyAction('TSLA'));
488
- * await waitAllActions();
489
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
490
- *
491
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
492
- * expect(store.state.portfolio).toEqual(['TSLA']);
493
- * dispatch(new BuyAction('IBM'));
494
- * dispatch(new SellAction('TSLA'));
495
- * await store.waitAllActionTypes([BuyAction, SellAction]);
496
- * expect(store.state.portfolio).toEqual(['IBM']);
497
- *
498
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
499
- * dispatch(new BuyAction('IBM'));
500
- * dispatch(new BuyAction('TSLA'));
501
- * await store.waitAllActions();
502
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
503
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
504
- *
505
- * // Dispatches two actions in PARALLEL and wait for them:
506
- * let action1 = new BuyAction('IBM');
507
- * let action2 = new SellAction('TSLA');
508
- * dispatch(action1);
509
- * dispatch(action2);
510
- * await store.waitAllActions([action1, action2]);
511
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
512
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
513
- *
514
- * // Dispatches two actions in SERIES and wait for them:
515
- * await dispatchAndWait(new BuyAction('IBM'));
516
- * await dispatchAndWait(new SellAction('TSLA'));
517
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
518
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
519
- *
520
- * // Wait until some action of a given type is dispatched.
521
- * dispatch(new DoALotOfStuffAction());
522
- * let action = await store.waitActionType(ChangeNameAction);
523
- * expect(action instanceof ChangeNameAction).toBe(true);
524
- * expect(action.status.isCompletedOk).toBe(true);
525
- * expect(store.state.name).toBe('Bill');
526
- *
527
- * // Wait until some action of the given types is dispatched.
528
- * dispatch(new ProcessStocksAction());
529
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
530
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
531
- * ```
532
- *
533
- * See also:
534
- * `waitCondition` - Waits until the state is in a given condition.
535
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
536
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
537
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
538
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
539
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
540
- *
541
- * You should only use this method in tests.
542
- */
543
- waitAllActions(actions: KissAction<St>[] | null, { completeImmediately, timeoutMillis }?: {
544
- completeImmediately?: boolean;
545
- timeoutMillis?: number | null;
546
- }): Promise<{
547
- actions: Set<KissAction<St>>;
548
- triggerAction: KissAction<St> | null;
549
- }>;
550
- /**
551
- * Returns a promise that completes when an action of the given type in NOT in progress
552
- * (it's not being dispatched):
553
- *
554
- * - If NO action of the given type is currently in progress when the method is called,
555
- * and `completeImmediately` is false (the default), this method will throw an error.
556
- *
557
- * - If NO action of the given type is currently in progress when the method is called,
558
- * and `completeImmediately` is true, the promise completes immediately, returns `null`,
559
- * and throws no error.
560
- *
561
- * - If an action of the given type is in progress, the promise completes when the action
562
- * finishes, and returns the action. You can use the returned action to check its `status`:
563
- *
564
- * ```dart
565
- * var action = await store.waitActionType(MyAction);
566
- * expect(action.status.originalError, isA<UserException>());
567
- * ```
568
- *
569
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
570
- * To disable the timeout, make it 0 or -1.
571
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
572
- *
573
- * Examples:
574
- *
575
- * ```ts
576
- * // Dispatches an actions that changes the state, then await for the state change:
577
- * expect(store.state.name).toBe('John');
578
- * dispatch(new ChangeNameAction("Bill"));
579
- * let action = await store.waitCondition((state) => state.name == "Bill");
580
- * expect(action instanceof ChangeNameAction).toBe(true);
581
- * expect(store.state.name).toBe('Bill');
582
- *
583
- * // Dispatches actions and wait until no actions are in progress.
584
- * dispatch(new BuyAction('IBM'));
585
- * dispatch(new BuyAction('TSLA'));
586
- * await waitAllActions();
587
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
588
- *
589
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
590
- * expect(store.state.portfolio).toEqual(['TSLA']);
591
- * dispatch(new BuyAction('IBM'));
592
- * dispatch(new SellAction('TSLA'));
593
- * await store.waitAllActionTypes([BuyAction, SellAction]);
594
- * expect(store.state.portfolio).toEqual(['IBM']);
595
- *
596
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
597
- * dispatch(new BuyAction('IBM'));
598
- * dispatch(new BuyAction('TSLA'));
599
- * await store.waitAllActions();
600
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
601
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
602
- *
603
- * // Dispatches two actions in PARALLEL and wait for them:
604
- * let action1 = new BuyAction('IBM');
605
- * let action2 = new SellAction('TSLA');
606
- * dispatch(action1);
607
- * dispatch(action2);
608
- * await store.waitAllActions([action1, action2]);
609
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
610
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
611
- *
612
- * // Dispatches two actions in SERIES and wait for them:
613
- * await dispatchAndWait(new BuyAction('IBM'));
614
- * await dispatchAndWait(new SellAction('TSLA'));
615
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
616
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
617
- *
618
- * // Wait until some action of a given type is dispatched.
619
- * dispatch(new DoALotOfStuffAction());
620
- * let action = await store.waitActionType(ChangeNameAction);
621
- * expect(action instanceof ChangeNameAction).toBe(true);
622
- * expect(action.status.isCompletedOk).toBe(true);
623
- * expect(store.state.name).toBe('Bill');
624
- *
625
- * // Wait until some action of the given types is dispatched.
626
- * dispatch(new ProcessStocksAction());
627
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
628
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
629
- * ```
630
- *
631
- * See also:
632
- * `waitCondition` - Waits until the state is in a given condition.
633
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
634
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
635
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
636
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
637
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
638
- *
639
- * You should only use this method in tests.
640
- */
641
- waitActionType(actionType: {
642
- new (...args: any[]): KissAction<St>;
643
- }, { completeImmediately, timeoutMillis }?: {
644
- completeImmediately?: boolean;
645
- timeoutMillis?: number | null;
646
- }): Promise<KissAction<St> | null>;
647
- /**
648
- * Returns a promise that completes when ALL actions of the given type are NOT in progress
649
- * (none of them is being dispatched):
650
- *
651
- * - If NO action of the given types is currently in progress when the method is called,
652
- * and `completeImmediately` is false (the default), this method will throw an error.
653
- *
654
- * - If NO action of the given type is currently in progress when the method is called,
655
- * and `completeImmediately` is true, the promise completes immediately and throws no error.
656
- *
657
- * - If any action of the given types is in progress, the promise completes only when
658
- * no action of the given types is in progress anymore.
659
- *
660
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
661
- * To disable the timeout, make it 0 or -1.
662
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
663
- *
664
- * Examples:
665
- *
666
- * ```ts
667
- * // Dispatches an actions that changes the state, then await for the state change:
668
- * expect(store.state.name).toBe('John');
669
- * dispatch(new ChangeNameAction("Bill"));
670
- * let action = await store.waitCondition((state) => state.name == "Bill");
671
- * expect(action instanceof ChangeNameAction).toBe(true);
672
- * expect(store.state.name).toBe('Bill');
673
- *
674
- * // Dispatches actions and wait until no actions are in progress.
675
- * dispatch(new BuyAction('IBM'));
676
- * dispatch(new BuyAction('TSLA'));
677
- * await waitAllActions();
678
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
679
- *
680
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
681
- * expect(store.state.portfolio).toEqual(['TSLA']);
682
- * dispatch(new BuyAction('IBM'));
683
- * dispatch(new SellAction('TSLA'));
684
- * await store.waitAllActionTypes([BuyAction, SellAction]);
685
- * expect(store.state.portfolio).toEqual(['IBM']);
686
- *
687
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
688
- * dispatch(new BuyAction('IBM'));
689
- * dispatch(new BuyAction('TSLA'));
690
- * await store.waitAllActions();
691
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
692
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
693
- *
694
- * // Dispatches two actions in PARALLEL and wait for them:
695
- * let action1 = new BuyAction('IBM');
696
- * let action2 = new SellAction('TSLA');
697
- * dispatch(action1);
698
- * dispatch(action2);
699
- * await store.waitAllActions([action1, action2]);
700
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
701
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
702
- *
703
- * // Dispatches two actions in SERIES and wait for them:
704
- * await dispatchAndWait(new BuyAction('IBM'));
705
- * await dispatchAndWait(new SellAction('TSLA'));
706
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
707
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
708
- *
709
- * // Wait until some action of a given type is dispatched.
710
- * dispatch(new DoALotOfStuffAction());
711
- * let action = await store.waitActionType(ChangeNameAction);
712
- * expect(action instanceof ChangeNameAction).toBe(true);
713
- * expect(action.status.isCompletedOk).toBe(true);
714
- * expect(store.state.name).toBe('Bill');
715
- *
716
- * // Wait until some action of the given types is dispatched.
717
- * dispatch(new ProcessStocksAction());
718
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
719
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
720
- * ```
721
- *
722
- * See also:
723
- * `waitCondition` - Waits until the state is in a given condition.
724
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
725
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
726
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
727
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
728
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
729
- *
730
- * You should only use this method in tests.
731
- */
732
- waitAllActionTypes(actionTypes: {
733
- new (...args: any[]): KissAction<any>;
734
- }[], { completeImmediately, timeoutMillis }?: {
735
- completeImmediately?: boolean;
736
- timeoutMillis?: number | null;
737
- }): Promise<void>;
738
- /**
739
- * Returns a promise which will complete when ANY action of the given types FINISHES
740
- * dispatching. IMPORTANT: This method is different from the other similar methods, because
741
- * it does NOT complete immediately if no action of the given types is in progress. Instead,
742
- * it waits until an action of the given types finishes dispatching, even if they
743
- * were not yet in progress when the method was called.
744
- *
745
- * This method returns the action that completed the promise, which you can use to check
746
- * its `status`.
747
- *
748
- * It's useful when the actions you are waiting for are not yet dispatched when you call this
749
- * method. For example, suppose action `StartAction` starts a process that takes some time
750
- * to run and then dispatches an action called `MyFinalAction`. You can then write:
751
- *
752
- * ```dart
753
- * dispatch(StartAction());
754
- * let action = await store.waitAnyActionTypeFinishes([MyFinalAction]);
755
- * expect(action.status.originalError).toBeInstanceOf(UserException>);
756
- * ```
757
- *
758
- * You may also provide a `timeoutMillis`, which by default is 10 minutes.
759
- * To disable the timeout, make it 0 or -1.
760
- * If you want, you can modify `TimeoutException.defaultTimeoutMillis` to change the default timeout.
761
- *
762
- * Examples:
763
- *
764
- * ```ts
765
- * // Dispatches an actions that changes the state, then await for the state change:
766
- * expect(store.state.name).toBe('John');
767
- * dispatch(new ChangeNameAction("Bill"));
768
- * let action = await store.waitCondition((state) => state.name == "Bill");
769
- * expect(action instanceof ChangeNameAction).toBe(true);
770
- * expect(store.state.name).toBe('Bill');
771
- *
772
- * // Dispatches actions and wait until no actions are in progress.
773
- * dispatch(new BuyAction('IBM'));
774
- * dispatch(new BuyAction('TSLA'));
775
- * await waitAllActions();
776
- * expect(state.stocks).toEqual(['IBM', 'TSLA']);
777
- *
778
- * // Dispatches two actions in PARALLEL and wait for their TYPES:
779
- * expect(store.state.portfolio).toEqual(['TSLA']);
780
- * dispatch(new BuyAction('IBM'));
781
- * dispatch(new SellAction('TSLA'));
782
- * await store.waitAllActionTypes([BuyAction, SellAction]);
783
- * expect(store.state.portfolio).toEqual(['IBM']);
784
- *
785
- * // Dispatches actions in PARALLEL and wait until no actions are in progress.
786
- * dispatch(new BuyAction('IBM'));
787
- * dispatch(new BuyAction('TSLA'));
788
- * await store.waitAllActions();
789
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
790
- * expect(store.state.portfolio.includes('TSLA')).toBe(true);
791
- *
792
- * // Dispatches two actions in PARALLEL and wait for them:
793
- * let action1 = new BuyAction('IBM');
794
- * let action2 = new SellAction('TSLA');
795
- * dispatch(action1);
796
- * dispatch(action2);
797
- * await store.waitAllActions([action1, action2]);
798
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
799
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
800
- *
801
- * // Dispatches two actions in SERIES and wait for them:
802
- * await dispatchAndWait(new BuyAction('IBM'));
803
- * await dispatchAndWait(new SellAction('TSLA'));
804
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
805
- * expect(store.state.portfolio.includes('TSLA')).toBe(false);
806
- *
807
- * // Wait until some action of a given type is dispatched.
808
- * dispatch(new DoALotOfStuffAction());
809
- * let action = await store.waitActionType(ChangeNameAction);
810
- * expect(action instanceof ChangeNameAction).toBe(true);
811
- * expect(action.status.isCompletedOk).toBe(true);
812
- * expect(store.state.name).toBe('Bill');
813
- *
814
- * // Wait until some action of the given types is dispatched.
815
- * dispatch(new ProcessStocksAction());
816
- * let action = await store.waitAnyActionTypeFinishes([BuyAction, SellAction]);
817
- * expect(store.state.portfolio.includes('IBM')).toBe(true);
818
- * ```
819
- *
820
- * See also:
821
- * `waitCondition` - Waits until the state is in a given condition.
822
- * `waitActionCondition` - Waits until the actions in progress meet a given condition.
823
- * `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
824
- * `waitActionType` - Waits until an action of a given type is NOT in progress.
825
- * `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
826
- * `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
827
- *
828
- * You should only use this method in tests.
829
- */
830
- waitAnyActionTypeFinishes(actionTypes: {
831
- new (...args: any[]): KissAction<St>;
832
- }[], { timeoutMillis }?: {
833
- completeImmediately?: boolean;
834
- timeoutMillis?: number | null;
835
- }): Promise<KissAction<St>>;
836
- }
837
- export {};
1
+ import { UserException } from './UserException';
2
+ import { Store } from './Store';
3
+ import { KissAction, ActionStatus, StatusOptions } from './KissAction';
4
+ import { Evt, EvtState } from './Evt';
5
+ /**
6
+ * Returns a part of the store state:
7
+ *
8
+ * ```ts
9
+ * const name = useSelect((state: State) => state.user.name);
10
+ * ```
11
+ *
12
+ * The component will rebuild only when the `name` changes, ignoring the
13
+ * change in other parts of the state. The selected value is compared with
14
+ * the previous one using `Object.is`, like React does. So `NaN` is equal
15
+ * to `NaN`, but `0` is different from `-0`.
16
+ *
17
+ * The selector must be pure: it must only read its `state` parameter, and return the same
18
+ * value for the same state. It may be an inline function, and may use props and local state.
19
+ * It should return a part of the state, not a new object: a new object is never `Object.is`
20
+ * the previous one, so the component would rebuild for every state change. Use `useObject`
21
+ * for that.
22
+ *
23
+ * Note: You can use `useSelect` and `useSelector` interchangeably.
24
+ * Prefer `useSelect` because it's shorter.
25
+ */
26
+ export declare function useSelect<St, T>(selector: (state: St) => T): T;
27
+ /**
28
+ * Returns a part of the store state:
29
+ *
30
+ * ```ts
31
+ * const name = useSelector((state: State) => state.user.name);
32
+ * ```
33
+ *
34
+ * The component will rebuild only when the `name` changes, ignoring the
35
+ * change in other parts of the state.
36
+ *
37
+ * Note: You can use `useSelect` and `useSelector` interchangeably.
38
+ * Prefer `useSelect` because it's shorter.
39
+ */
40
+ export declare function useSelector<St, T>(selector: (state: St) => T): T;
41
+ /**
42
+ * Returns an object (or an array, `Map` or `Set`) with some parts of the store state:
43
+ *
44
+ * ```ts
45
+ * const user = useObject((state: State) => ({ name: state.user.name, age: state.user.age }));
46
+ * return <div>{user.name} is {user.age} years old</div>;
47
+ * ```
48
+ *
49
+ * The component will rebuild only when the `name` or the `age` changes, ignoring the
50
+ * change in other parts of the state.
51
+ *
52
+ * Note: With `useSelect`, the same selector would rebuild the component for ALL state changes,
53
+ * since it creates a new object each time. Instead, `useObject` compares the new object with
54
+ * the previous one, value by value (with `Object.is`). If they have the same values, it
55
+ * returns the previous object, and the component doesn't rebuild. This also works if the
56
+ * selector returns an array: `useObject((state: State) => [state.name, state.age])`, or a
57
+ * `Map` or a `Set`, whose entries are compared in order.
58
+ *
59
+ * Note the values themselves are compared by identity. So, the selector should return parts
60
+ * of the state, and not create new objects or arrays for its values.
61
+ *
62
+ * Only plain objects, arrays, `Map`s and `Set`s are compared value by value. Anything else,
63
+ * like a `Date`, a class instance, or a subclass of `Map` or `Set`, is compared by identity,
64
+ * like `useSelect` does. So, `useObject((state: State) => new Point(state.x, state.y))` would
65
+ * rebuild the component for ALL state changes.
66
+ *
67
+ * For this reason, the selector's type only accepts a plain object, an array, a `Map` or a
68
+ * `Set` (or `null` or `undefined`), and a class instance, a `Date`, a string, a number or a
69
+ * function doesn't compile. Note an object whose type is an `interface` doesn't compile either,
70
+ * since TypeScript can't tell it apart from a class instance. Declare it with `type` instead.
71
+ *
72
+ * While the values are the same, `useObject` keeps returning the object it returned before,
73
+ * so you can use it in the dependencies of an effect, or pass it to a memoized component.
74
+ */
75
+ export declare function useObject<St, T extends UseObjectValue>(selector: (state: St) => T): T;
76
+ type UseObjectValue = Record<string, unknown> | readonly unknown[] | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | null | undefined;
77
+ /**
78
+ * Returns the whole store state:
79
+ *
80
+ * ```ts
81
+ * const state = useAllState<State>();
82
+ * const name = state.user.name;
83
+ * ```
84
+ *
85
+ * While that's convenient, the above code will rebuild the component for all state changes,
86
+ * no matter if the name changed or not. For this reason, prefer `useSelector`:
87
+ *
88
+ * ```ts
89
+ * const name = useSelector((state: State) => state.user.name);
90
+ * ```
91
+ *
92
+ * Now it will rebuild only when the name changes.
93
+ */
94
+ export declare function useAllState<St>(): St;
95
+ /**
96
+ * Returns an object with all the dispatch and wait methods of the store:
97
+ *
98
+ * - `dispatch` - Dispatches an action, to potentially change the state.
99
+ * - `dispatchAndWait` - Dispatches an action and returns a promise that resolves when the action finishes.
100
+ * - `dispatchSync` - Same as the regular dispatch, except it throws an error if the action is ASYNC.
101
+ * - `dispatchWhen` - Waits until the state is in a given condition, and then dispatches an action.
102
+ * - `dispatchAll` - Dispatches all given actions in parallel.
103
+ * - `dispatchAndWaitAll` - Dispatches all given actions, and returns a promise that resolves when they all finish.
104
+ * - `waitCondition` - Waits until the state is in a given condition.
105
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
106
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
107
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
108
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
109
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
110
+ *
111
+ * Example:
112
+ *
113
+ * ```js
114
+ * const store = useStore();
115
+ * store.dispatch(new MyAction());
116
+ * await store.dispatchAndWait(new MyAction());
117
+ * store.dispatchSync(new MyAction());
118
+ * store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
119
+ * await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
120
+ * await store.waitCondition((state) => state.user.name === "Bill", { timeoutMillis: 1000 });
121
+ * await store.waitAllActionTypes([BuyAction, SellAction]);
122
+ * ```
123
+ *
124
+ * The methods also work when destructured: `const { dispatch, dispatchAndWait } = useStore();`.
125
+ *
126
+ * The object also has `store`, which is the store itself, with its `state` and all its other
127
+ * methods:
128
+ *
129
+ * ```js
130
+ * const { store } = useStore();
131
+ * console.log(store.actionsInProgress());
132
+ * ```
133
+ *
134
+ * IMPORTANT: `useStore` doesn't make the component re-render when the state changes. So, read
135
+ * `store.state` only in event handlers, effects and callbacks, never to render the component.
136
+ * To render it, use the hooks that re-render the component when needed:
137
+ * - To get the state: `useSelect`, `useObject` or `useAllState`
138
+ * - To know if actions are running: `useIsWaiting`
139
+ * - To deal with exceptions: `useIsFailed`, `useExceptionFor` and `useClearExceptionFor`
140
+ * - To use `<Suspense>` and error boundaries instead: `useSuspense`
141
+ *
142
+ * See also:
143
+ * - `useDispatch()` - Hook equivalent to `useStore().dispatch`
144
+ * - `useDispatchAndWait` - Hook equivalent to `useStore().dispatchAndWait`
145
+ * - `useDispatchSync` - Hook equivalent to `useStore().dispatchSync`
146
+ * - `useDispatchWhen` - Hook equivalent to `useStore().dispatchWhen`
147
+ * - `useDispatchAll` - Hook equivalent to `useStore().dispatchAll`
148
+ * - `useDispatchAndWaitAll` - Hook equivalent to `useStore().dispatchAndWaitAll`
149
+ * - `useStoreEffect` - To dispatch actions when the component mounts, when some values change,
150
+ * and when it unmounts.
151
+ */
152
+ export declare function useStore(): StoreDispatchers<any>;
153
+ /**
154
+ * @deprecated Use `useDispatch`. Note you also have `useDispatchAndWait` and `useDispatchSync`.
155
+ */
156
+ export declare function useDispatcher(): (action: KissAction<any>) => void;
157
+ /**
158
+ * Returns a function that dispatches an action, to potentially change the state:
159
+ *
160
+ * ```ts
161
+ * const dispatch = useDispatch();
162
+ * dispatch(new MyAction());
163
+ * ```
164
+ *
165
+ * This also works:
166
+ *
167
+ * ```ts
168
+ * const store = useStore();
169
+ * store.dispatch(new MyAction());
170
+ * ```
171
+ *
172
+ * To dispatch actions when the component mounts, when some values change, and when it
173
+ * unmounts, see `useStoreEffect`.
174
+ *
175
+ * See also:
176
+ * - `dispatchAll` which dispatches all given actions in parallel.
177
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
178
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
179
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
180
+ */
181
+ export declare function useDispatch<St = any>(): (action: KissAction<St>) => void;
182
+ /**
183
+ * Options for `useStoreEffect`, to run code when the component mounts, when its `deps` change,
184
+ * and when it unmounts. See `useStoreEffect`.
185
+ */
186
+ export interface UseStoreEffectOptions<St, D> {
187
+ /**
188
+ * A single value, or an array of values. When they change, `onDepsChange` is called.
189
+ * They are compared with `Object.is`, like React's dependencies. So, don't create new objects
190
+ * or arrays in each render, or they will be considered changed in every render.
191
+ */
192
+ deps?: D;
193
+ /** Called once, when the component mounts (but only after the store is ready). */
194
+ onMount?: (store: Store<St>) => unknown;
195
+ /**
196
+ * Called when `deps` change (but only after `onMount`). It gets the old `deps`.
197
+ * The new values are the ones in your component.
198
+ */
199
+ onDepsChange?: (store: Store<St>, oldDeps: D) => unknown;
200
+ /** Called once, when the component unmounts (but only if `onMount` was called). */
201
+ onUnmount?: (store: Store<St>) => unknown;
202
+ /**
203
+ * Called when the app is focused again (in the browser, when the document becomes visible:
204
+ * the user comes back to the tab, or restores the window), while the component is mounted.
205
+ * Not called on mount. See `store.isFocused` and `focusSource` in `createStore`.
206
+ */
207
+ onFocus?: (store: Store<St>) => unknown;
208
+ /**
209
+ * Called when the app loses focus (in the browser, when the document becomes hidden), while
210
+ * the component is mounted. See `store.isFocused`.
211
+ */
212
+ onBlur?: (store: Store<St>) => unknown;
213
+ /**
214
+ * Called when the app is online again, while the component is mounted. Not called on mount.
215
+ * See `store.isOnline` and `onlineSource` in `createStore`.
216
+ */
217
+ onOnline?: (store: Store<St>) => unknown;
218
+ /** Called when the app goes offline, while the component is mounted. See `store.isOnline`. */
219
+ onOffline?: (store: Store<St>) => unknown;
220
+ }
221
+ /**
222
+ * Use `useStoreEffect` instead of a `useEffect` to dispatch actions when the component mounts
223
+ * (`onMount`), when some values change (`deps` and `onDepsChange`), and when it unmounts
224
+ * (`onUnmount`):
225
+ *
226
+ * ```tsx
227
+ * useStoreEffect({
228
+ * deps: userId,
229
+ * onMount: (store) => store.dispatch(new LoadUser(userId)),
230
+ * onDepsChange: (store, oldUserId) => {
231
+ * store.dispatch(new StopListening(oldUserId));
232
+ * store.dispatch(new LoadUser(userId));
233
+ * },
234
+ * onUnmount: (store) => store.dispatch(new CleanResources()),
235
+ * });
236
+ * ```
237
+ *
238
+ * If `deps` is an array, `onDepsChange` gets the old array:
239
+ *
240
+ * ```tsx
241
+ * useStoreEffect({
242
+ * deps: [userId, filter],
243
+ * onMount: (store) => store.dispatch(new LoadUser(userId, filter)),
244
+ * onDepsChange: (store, [oldUserId, oldFilter]) => {
245
+ * if (userId !== oldUserId) {
246
+ * store.dispatch(new StopListening(oldUserId));
247
+ * store.dispatch(new LoadUser(userId, filter));
248
+ * }
249
+ * else if (filter !== oldFilter) store.dispatch(new ApplyFilter(filter));
250
+ * },
251
+ * });
252
+ * ```
253
+ *
254
+ * All of them are optional, and get the store, so you can use any of its dispatch methods,
255
+ * and read its current `state`. They may be async. To type the state, type the store:
256
+ * `onMount: (store: Store<State>) => ...`. The hook returns nothing. To also dispatch actions
257
+ * from event handlers, use `useDispatch`, `useStore`, etc.
258
+ *
259
+ * Note you can still dispatch actions from a `useEffect`, as usual, if you prefer.
260
+ * `useStoreEffect` is just more convenient, because:
261
+ *
262
+ * - They only run after the store is ready (see `useIsStoreReady`). If the store is not ready
263
+ * when the component mounts, `onMount` is called as soon as it is. If the component unmounts
264
+ * before that, none of them is called.
265
+ *
266
+ * - They are called in order: `onMount`, then `onDepsChange` (any number of times), then
267
+ * `onUnmount`. But if one of them is async, it's not awaited (see below).
268
+ * `onMount` and `onUnmount` run once, even in React's `StrictMode`, which mounts components
269
+ * twice during development. And `onDepsChange` runs once per change.
270
+ *
271
+ * - Like a `useEffect` cleanup, `onUnmount` runs when the component unmounts, before the
272
+ * `onMount` of a component mounted in the same render (in a route switch, for example).
273
+ *
274
+ * When they run, compared to a `useEffect` (in production and in development):
275
+ *
276
+ * - `onMount` runs at the same time as a `useEffect(..., [])` called in the same place of the
277
+ * component, if the store is ready. If not, it runs when the store becomes ready.
278
+ *
279
+ * - `onDepsChange` runs at the same time as a `useEffect(..., [deps])`, but not after the first
280
+ * render. The deps are compared like React does: each value with `Object.is`.
281
+ *
282
+ * - `onUnmount` runs at the same time as the cleanup of a `useEffect`, with one exception:
283
+ * if the component unmounts in the same synchronous run as its mount (before any microtask),
284
+ * `onUnmount` waits one microtask. This is when `StrictMode` does its fake unmount, so if the
285
+ * component mounts again in that time, `onUnmount` is cancelled, and `onMount` is not called
286
+ * again. A real unmount that soon is rare, but its `onUnmount` also runs one microtask later.
287
+ *
288
+ * - So the actions they dispatch are dispatched at the same time as from a `useEffect`. A sync
289
+ * action changes the state before `onMount`, `onDepsChange` or `onUnmount` returns.
290
+ *
291
+ * - They are not awaited. If one of them is async, the next one may run before it finishes.
292
+ * For example, `onUnmount` may run while an async `onMount` is still waiting for an action.
293
+ *
294
+ * - Their errors are not caught, as in a `useEffect`. A sync error goes to React, which shows
295
+ * the nearest error boundary (except that React 18 doesn't give an error thrown by
296
+ * `onUnmount` while the component unmounts to the boundary: it logs it as an internal React
297
+ * error; React 19 fixed it). A rejected promise is an unhandled promise rejection. And when
298
+ * `onMount` waits for the store to be ready, or `onUnmount` waits a microtask (see above),
299
+ * even a sync error is an unhandled promise rejection. If `onMount` throws a sync error when
300
+ * the component mounts (the store is ready), `onUnmount` is not called, as the cleanup of a
301
+ * `useEffect` whose setup throws.
302
+ *
303
+ * - They are the ones from the latest render, so they see its values.
304
+ *
305
+ * - Some React features disconnect the effects and connect them again, without a real unmount.
306
+ * As for a `useEffect`, this calls `onUnmount` and then `onMount` again. For example, in
307
+ * development, Fast Refresh does it to a component when you edit its code. And `<Activity>`
308
+ * does it when it hides the component and shows it again.
309
+ *
310
+ * - A component can call `useStoreEffect` more than once. They run in the order they are called.
311
+ *
312
+ * Note: Changing `deps` doesn't call `onMount` again. If you want to dispatch the same actions
313
+ * on mount and when `deps` change, call the same function from both `onMount` and
314
+ * `onDepsChange`. Each of them sees the values from the latest render.
315
+ *
316
+ * To reload the data on screen when the user comes back to the tab, or when the internet comes
317
+ * back, use `onFocus` and `onOnline` (and `onBlur` and `onOffline` for the opposite):
318
+ *
319
+ * ```tsx
320
+ * useStoreEffect({
321
+ * onMount: (store) => store.dispatch(new LoadPrices()),
322
+ * onFocus: (store) => store.dispatch(new LoadPrices()),
323
+ * onOnline: (store) => store.dispatch(new LoadPrices()),
324
+ * });
325
+ * ```
326
+ *
327
+ * - They are called on the transitions only (hidden → visible, offline → online, and back),
328
+ * never on mount, and only while the component is mounted and after `onMount` was called
329
+ * (so, after the store is ready). Like the other callbacks, they get the store, see the
330
+ * values of the latest render, and are not awaited.
331
+ *
332
+ * - To only reload when the data is old, give the action a `fresh` period: a focus within the
333
+ * period is then aborted silently. Without `fresh`, the action runs on every focus.
334
+ *
335
+ * - What "focused" and "online" mean comes from the store: `store.isFocused` and
336
+ * `store.isOnline`, with `focusSource` and `onlineSource` in `createStore` to change the
337
+ * defaults (for example, in React Native). In tests, drive them with `store.setFocused()` and
338
+ * `store.setOnline()`.
339
+ *
340
+ * - A component that doesn't give these callbacks doesn't make the store listen to the focus
341
+ * and online sources.
342
+ */
343
+ export declare function useStoreEffect<St = any, const D = undefined>(options: UseStoreEffectOptions<St, D>): void;
344
+ /**
345
+ * Dispatches an action and returns a promise that resolves when the action finishes.
346
+ * While the state change from the action's reducer will have been applied when the promise
347
+ * resolves, other independent processes that the action may have started may still be in
348
+ * progress.
349
+ *
350
+ * Usage:
351
+ * ```ts
352
+ * const dispatchAndWait = useDispatchAndWait();
353
+ * await dispatchAndWait(new MyAction());
354
+ * ```
355
+ *
356
+ * See also:
357
+ * - `dispatch` which dispatches both sync and async actions.
358
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
359
+ * - `dispatchAll` which dispatches all given actions in parallel.
360
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
361
+ */
362
+ export declare function useDispatchAndWait(): (action: KissAction<any>) => Promise<ActionStatus>;
363
+ /**
364
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
365
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
366
+ * ALL actions finish.
367
+ *
368
+ * ```ts
369
+ * const dispatchAndWaitAll = useDispatchAndWaitAll();
370
+ * await dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
371
+ * ```
372
+ *
373
+ * Note: While the state change from the action's reducers will have been applied when the
374
+ * Promise resolves, other independent processes that the action may have started may still
375
+ * be in progress.
376
+ *
377
+ * See also:
378
+ * - `dispatch` which dispatches both sync and async actions.
379
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
380
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
381
+ * - `dispatchAll` which dispatches all given actions in parallel.
382
+ */
383
+ export declare function useDispatchAndWaitAll(): (action: KissAction<any>[]) => Promise<KissAction<any>[]>;
384
+ /**
385
+ * Waits until the store state meets a certain condition, and then dispatches an action.
386
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
387
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
388
+ * the condition, so no other action can change the state in between.
389
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
390
+ * dispatched one after the other, and each condition is checked again right before its
391
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
392
+ *
393
+ * ```ts
394
+ * const dispatchWhen = useDispatchWhen();
395
+ * dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
396
+ * ```
397
+ *
398
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
399
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
400
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
401
+ * timeout is logged. To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`),
402
+ * but note that while it waits, the condition runs on every state change.
403
+ *
404
+ * ```ts
405
+ * dispatchWhen(
406
+ * new BuyStock('IBM'),
407
+ * (state) => state.stocks.getPrice('IBM') >= 100,
408
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
409
+ * );
410
+ * ```
411
+ *
412
+ * Note: The wait is NOT cancelled when the component unmounts.
413
+ *
414
+ * See also:
415
+ * - `dispatch` which dispatches both sync and async actions.
416
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
417
+ */
418
+ export declare function useDispatchWhen(): (action: KissAction<any>, condition: (state: any) => boolean, options: {
419
+ timeoutMillis: number;
420
+ onTimeout?: () => void;
421
+ }) => void;
422
+ /**
423
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
424
+ * the store state.
425
+ *
426
+ * ```ts
427
+ * const dispatchAll = useDispatchAll();
428
+ * dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
429
+ * ```
430
+ *
431
+ * See also:
432
+ * - `dispatch` which dispatches both sync and async actions.
433
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
434
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
435
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
436
+ */
437
+ export declare function useDispatchAll(): (action: KissAction<any>[]) => KissAction<any>[];
438
+ /**
439
+ * Dispatches the given action to the Redux store, to potentially change the state.
440
+ *
441
+ * This is exactly the same as the regular `dispatch`, except for the fact it
442
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
443
+ * if any of its `reduce()` or `before()` methods return a Promise.
444
+ *
445
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
446
+ * action is SYNC, which means the state gets changed right after the dispatch call.
447
+ *
448
+ * See also:
449
+ * - `dispatch` which dispatches both sync and async actions.
450
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
451
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
452
+ * - `dispatchAll` which dispatches all given actions in parallel.
453
+ */
454
+ export declare function useDispatchSync(): (action: KissAction<any>) => void;
455
+ /**
456
+ * You can use `isWaiting` and pass it an action `type`:
457
+ * - It returns true if an action of the given type (or of a subclass) is currently being processed.
458
+ * - It returns false if no action of the given type is currently being processed.
459
+ * - This is only useful for ASYNC actions. A SYNC action finishes before `dispatch` returns, so
460
+ * outside of it, `isWaiting` is always `false` for it, and components never see it as `true`.
461
+ *
462
+ * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
463
+ *
464
+ * ```ts
465
+ * const isWaiting = useIsWaiting(MyAction);
466
+ * if (isWaiting) { ... } // Show a spinner
467
+ * ```
468
+ *
469
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
470
+ * `KissAction.statusKey`): `useIsWaiting(LoadUser, { statusKey: userId })`.
471
+ */
472
+ export declare function useIsWaiting(type: abstract new (...args: any[]) => KissAction<any>, options?: StatusOptions): boolean;
473
+ /**
474
+ * Returns true if the store is ready, and false while it's still loading the persisted state.
475
+ * See `Store.ready()`.
476
+ *
477
+ * You can show the UI before the store is ready, using the initial-state. But dispatching an
478
+ * action before the store is ready throws a `StoreException`. Use this hook to show a loading
479
+ * state, and to disable the buttons that dispatch actions:
480
+ *
481
+ * ```tsx
482
+ * const isReady = useIsStoreReady();
483
+ * if (!isReady) return <Spinner/>;
484
+ * // or: <button disabled={!isReady} onClick={() => dispatch(new AddTodo())}>Add</button>
485
+ * ```
486
+ *
487
+ * A store without a persistor is always ready. Once ready, a store stays ready.
488
+ */
489
+ export declare function useIsStoreReady(): boolean;
490
+ /**
491
+ * Returns true if the app is focused (in the browser, if the document is visible: the user is
492
+ * on the tab that shows the app). See `store.isFocused`. The component re-renders when it
493
+ * changes. On the server, it's always `true`.
494
+ *
495
+ * To dispatch an action when the app is focused again, use `useStoreEffect` with `onFocus`.
496
+ */
497
+ export declare function useIsFocused(): boolean;
498
+ /**
499
+ * Returns true if the app is online. See `store.isOnline`. The component re-renders when it
500
+ * changes, so you can show an "offline" banner. On the server, it's always `true`.
501
+ *
502
+ * ```tsx
503
+ * const isOnline = useIsOnline();
504
+ * if (!isOnline) return <Banner>You are offline</Banner>;
505
+ * ```
506
+ *
507
+ * To dispatch an action when the internet comes back, use `useStoreEffect` with `onOnline`.
508
+ */
509
+ export declare function useIsOnline(): boolean;
510
+ /**
511
+ * Returns the environment of the store (production, staging, testing, etc), given to
512
+ * `createStore` as `environment`, or `undefined`. For example, to show a debug banner:
513
+ *
514
+ * ```ts
515
+ * const env = useEnvironment<Environment>();
516
+ * if (env !== Environment.production) return <DebugBanner />;
517
+ * ```
518
+ *
519
+ * Give it the type of the environment, as above. It never re-renders the component, since
520
+ * the environment doesn't change while the app runs.
521
+ *
522
+ * See also: `useConfiguration`. There is no hook for the dependencies, since components
523
+ * should usually not need them. In actions, read them with `this.store.environment`,
524
+ * `this.store.configuration` and `this.store.dependencies`.
525
+ */
526
+ export declare function useEnvironment<E = unknown>(): E;
527
+ /**
528
+ * Returns the configuration of the store (feature flags and other configuration values),
529
+ * created by the `configuration` factory given to `createStore`, or `undefined`. For
530
+ * example, to hide a feature behind a flag:
531
+ *
532
+ * ```ts
533
+ * const config = useConfiguration<Config>();
534
+ * if (config.showAdminConsole) return <AdminConsole />;
535
+ * ```
536
+ *
537
+ * Give it the type of the configuration, as above. It never re-renders the component, since
538
+ * the configuration doesn't change while the app runs.
539
+ *
540
+ * See also: `useEnvironment`.
541
+ */
542
+ export declare function useConfiguration<C = unknown>(): C;
543
+ /**
544
+ * Returns true if the given action `type` failed, with any error, not only with a
545
+ * `UserException`. Use `exceptionFor` to get the error, if it was a `UserException`.
546
+ * An error swallowed by `wrapError` or the `errorObserver` (they returned `null`), and
547
+ * an `AbortDispatchException`, don't count as failures.
548
+ * Note: This method uses the EXACT action type. Subtypes are not considered.
549
+ *
550
+ * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see
551
+ * `KissAction.statusKey`): `useIsFailed(LoadUser, { statusKey: userId })`.
552
+ */
553
+ export declare function useIsFailed(type: {
554
+ new (...args: any[]): KissAction<any>;
555
+ }, options?: StatusOptions): boolean;
556
+ /**
557
+ * Returns the `UserException` of the `type` that failed. Returns `null` if it didn't fail,
558
+ * or if it failed with an error that is not a `UserException` (in that case, `isFailed` is
559
+ * still true).
560
+ * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
561
+ *
562
+ * The exception is the object the action threw (or the one `wrapError` or the `errorObserver`
563
+ * returned). It's returned as is: don't change it after throwing it, since React compares it
564
+ * by identity to know if the component must rebuild.
565
+ *
566
+ * Pass `{ statusKey }` to get the exception of the failure with that `statusKey` (see
567
+ * `KissAction.statusKey`): `useExceptionFor(LoadUser, { statusKey: userId })`. Without it,
568
+ * if actions with different keys failed, you get the `UserException` of the most recent
569
+ * failure.
570
+ */
571
+ export declare function useExceptionFor(type: {
572
+ new (...args: any[]): KissAction<any>;
573
+ }, options?: StatusOptions): UserException | null;
574
+ /**
575
+ * Removes the exact given action `type` from the list of action types that failed.
576
+ * Note it clears the EXACT given type. Subtypes are not considered.
577
+ *
578
+ * Even if you never call this method explicitly, just dispatching an action already clears that action type
579
+ * from the list of failing action types. But you can call this method explicitly if you want to clear the
580
+ * action type before it's used again.
581
+ *
582
+ * Usage:
583
+ * ```ts
584
+ * const clearExceptionFor = useClearExceptionFor();
585
+ * clearExceptionFor(MyAction);
586
+ * clearExceptionFor(AnotherAction);
587
+ * ```
588
+ *
589
+ * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see
590
+ * `KissAction.statusKey`): `clearExceptionFor(LoadUser, { statusKey: userId })`. Without it,
591
+ * all the failures of the type are cleared, whatever their keys.
592
+ */
593
+ export declare function useClearExceptionFor(): (type: {
594
+ new (...args: any[]): KissAction<any>;
595
+ }, options?: StatusOptions) => void;
596
+ /**
597
+ * Options for `useSuspense`.
598
+ *
599
+ * - `statusKey`: Only consider the actions whose `statusKey` is equal to this one. Leave it
600
+ * out (or pass `undefined`) to consider all actions of the type. See `KissAction.statusKey`.
601
+ * - `throwErrors`: When `true` (the default), if the action failed, the error is thrown to the
602
+ * nearest error boundary. Pass `false` to not throw, and use `useIsFailed` or
603
+ * `useExceptionFor` instead.
604
+ */
605
+ export type SuspenseOptions = StatusOptions & {
606
+ throwErrors?: boolean;
607
+ };
608
+ /**
609
+ * Suspends the component while an action of the given `type` is in progress, and throws the
610
+ * error to the nearest error boundary if the action failed. It's the alternative to
611
+ * `useIsWaiting` and `useIsFailed` for apps that prefer React's `<Suspense>` and error
612
+ * boundaries, like TanStack Query's `useSuspenseQuery`:
613
+ *
614
+ * ```tsx
615
+ * function UserName({ userId }: { userId: string }) {
616
+ * useSuspense(LoadUser, { statusKey: userId });
617
+ * const user = useSelect((state: State) => state.users[userId]);
618
+ * return <p>{user.name}</p>;
619
+ * }
620
+ *
621
+ * function UserCard({ userId }: { userId: string }) {
622
+ * return (
623
+ * <ErrorBoundary fallback={<p>Loading failed.</p>}>
624
+ * <Suspense fallback={<Spinner />}>
625
+ * <UserName userId={userId} />
626
+ * </Suspense>
627
+ * </ErrorBoundary>
628
+ * );
629
+ * }
630
+ * ```
631
+ *
632
+ * - While an action of the type (or of a subclass, like `useIsWaiting`) is in progress, the
633
+ * hook throws a promise. React stops the render there (the code after the hook doesn't run),
634
+ * shows the `fallback` of the nearest `<Suspense>` above the component, and renders the
635
+ * component again when the action finishes. The promise is the same object on every render
636
+ * while the action runs, and resolves when it finishes.
637
+ * - Otherwise, if the last action of the exact type failed (like `useIsFailed`: with any
638
+ * error, not only a `UserException`), the hook throws that error. The nearest error boundary
639
+ * above the component catches it. The failure stays recorded in the store, like with
640
+ * `useIsFailed`: dispatching the action again clears it (and makes the component suspend),
641
+ * and so does `clearExceptionFor`. So a "retry" button in the boundary should dispatch the
642
+ * action again, and then reset the boundary. Pass `{ throwErrors: false }` to not throw, and
643
+ * use `useIsFailed` or `useExceptionFor` instead.
644
+ * - Otherwise, the hook returns, and the component renders normally.
645
+ *
646
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
647
+ * `KissAction.statusKey`): `useSuspense(LoadUser, { statusKey: userId })`. Without it, the
648
+ * component suspends while any action of the type runs, and throws its most recent failure.
649
+ *
650
+ * On the server and while hydrating, the hook never suspends or throws, like `useIsWaiting`
651
+ * and `useIsFailed` are `false` there (see `StoreProviderProps.serverState`). After hydration,
652
+ * it follows the live store.
653
+ *
654
+ * Note: a component that suspends on its first render is thrown away and rendered again from
655
+ * the start, so its local state (`useState`, `useRef`) is lost. A component that already
656
+ * rendered keeps its state while suspended. This is how React's Suspense works.
657
+ */
658
+ export declare function useSuspense(type: abstract new (...args: any[]) => KissAction<any>, options?: SuspenseOptions): void;
659
+ /**
660
+ * Handles an event (`Evt` or `EvtState`) from the state, by calling the `callback` with its
661
+ * value, once per event:
662
+ *
663
+ * ```tsx
664
+ * function Feed() {
665
+ * const listRef = useRef<HTMLDivElement>(null);
666
+ * const inputRef = useRef<HTMLInputElement>(null);
667
+ *
668
+ * useEvent((state: State) => state.scrollToTopEvt, () => listRef.current?.scrollTo({ top: 0 }));
669
+ * useEvent((state: State) => state.changeTextEvt, (text) => { inputRef.current!.value = text; });
670
+ * ...
671
+ * }
672
+ * ```
673
+ *
674
+ * Events are for an action to ask the UI to do something once, that is not a state change:
675
+ * scroll a list, clear or focus an input, open a dialog. See `Evt` for how actions create them.
676
+ *
677
+ * The `selector` returns one event from the state (or `null`/`undefined`, to handle nothing).
678
+ * The `callback` runs in an effect, after the render that shows the new state is committed, like
679
+ * a `useEffect` (use `useLayoutEvent` to run it before the browser paints, like a
680
+ * `useLayoutEffect`). It's always the callback of the latest render, so it sees the latest props.
681
+ *
682
+ * For an `Evt`, the callback is called once per event, and then the event is **spent**:
683
+ *
684
+ * - A new event while the component is mounted: fires once.
685
+ * - An event created before the component mounts: fires once, when it mounts.
686
+ * - The component remounts later: doesn't fire, since the event is spent.
687
+ * - Two components use the same event: only the first one fires. Create two events for that.
688
+ * - Unrelated re-renders: doesn't fire.
689
+ * - In React's `StrictMode`, which runs effects twice in development: fires once.
690
+ *
691
+ * For an `EvtState`, the callback is called when the state has a different `EvtState` than the
692
+ * last one the component saw. It fires in every mounted component that uses it, but not when the
693
+ * component mounts or remounts, so events that happen while it's not mounted are missed.
694
+ *
695
+ * The store keeps which events were spent (see `store.isEventSpent`), so the events and the state
696
+ * stay immutable. Nothing is spent during render: React may throw a render away, so a render
697
+ * can't spend the event. That's why there is no way to consume an event in render, only this hook.
698
+ */
699
+ export declare function useEvent<St, T>(selector: (state: St) => Evt<T> | EvtState<T> | null | undefined, callback: (value: T) => void): void;
700
+ /**
701
+ * The same as `useEvent`, but the `callback` runs in a layout effect, before the browser paints
702
+ * (like a `useLayoutEffect`). Use it when the UI work would otherwise flicker: a scroll, a focus,
703
+ * a measurement. Like `useLayoutEffect`, it does nothing on the server, and React 18 warns about it
704
+ * there. Prefer `useEvent` when the timing doesn't matter.
705
+ */
706
+ export declare function useLayoutEvent<St, T>(selector: (state: St) => Evt<T> | EvtState<T> | null | undefined, callback: (value: T) => void): void;
707
+ /**
708
+ * Helper class that allows us to write:
709
+ *
710
+ * ```js
711
+ * const store = useStore();
712
+ * store.dispatch(new MyAction());
713
+ * store.dispatchSync(new MyAction());
714
+ * await store.dispatchAndWait(new MyAction());
715
+ * store.dispatchAll([new MyAction(), new OtherAction()]);
716
+ * await store.dispatchAndWaitAll([new MyAction(), new OtherAction()]);
717
+ * ```
718
+ */
719
+ declare class StoreDispatchers<St> {
720
+ store: Store<St>;
721
+ constructor(store: Store<St>);
722
+ /**
723
+ * Aborts all the actions of the given `type` (or of a subclass) that are in progress. Each
724
+ * one finishes silently: its `abortSignal` is aborted, its result is ignored, and so are its
725
+ * errors. See `Store.abort`.
726
+ *
727
+ * ```tsx
728
+ * const { abort } = useStore();
729
+ * <button onClick={() => abort(UploadFile)}>Cancel</button>
730
+ * ```
731
+ *
732
+ * Pass `{ statusKey }` to abort only the actions with that `statusKey`.
733
+ */
734
+ abort<T extends KissAction<St>>(type: abstract new (...args: any[]) => T, options?: StatusOptions): void;
735
+ /**
736
+ * Dispatches the action to the Redux store, to potentially change the state.
737
+ */
738
+ dispatch(action: KissAction<any>): void;
739
+ /**
740
+ * Waits until the store state meets a certain condition, and then dispatches an action.
741
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
742
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
743
+ * the condition, so no other action can change the state in between.
744
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
745
+ * dispatched one after the other, and each condition is checked again right before its
746
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
747
+ *
748
+ * ```ts
749
+ * store.dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
750
+ * ```
751
+ *
752
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
753
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
754
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
755
+ * timeout is logged with `Store.log()`. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
756
+ * (or -1, or `Infinity`), but note that while it waits, the condition runs on every state change.
757
+ * A `logOut()` cancels the `dispatchWhen`s that are still waiting: their action is not
758
+ * dispatched, and their `onTimeout` is not called.
759
+ *
760
+ * ```ts
761
+ * store.dispatchWhen(
762
+ * new BuyStock('IBM'),
763
+ * (state) => state.stocks.getPrice('IBM') >= 100,
764
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
765
+ * );
766
+ * ```
767
+ */
768
+ dispatchWhen(action: KissAction<St>, condition: (state: St) => boolean, options: {
769
+ timeoutMillis: number;
770
+ onTimeout?: () => void;
771
+ }): void;
772
+ /**
773
+ * Dispatches an action and returns a promise that resolves when the action finishes.
774
+ * While the state change from the action's reducer will have been applied when the promise
775
+ * resolves, other independent processes that the action may have started may still be in
776
+ * progress.
777
+ *
778
+ * Usage: `await store.dispatchAndWait(new MyAction())`.
779
+ */
780
+ dispatchAndWait(action: KissAction<any>): Promise<ActionStatus>;
781
+ /**
782
+ * Dispatches the given action to the Redux store, to potentially change the state.
783
+ *
784
+ * This is exactly the same as the regular `dispatch`, except for the fact it
785
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
786
+ * if any of its `reduce()` or `before()` methods return a Promise.
787
+ *
788
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
789
+ * action is SYNC, which means the state gets changed right after the dispatch call.
790
+ */
791
+ dispatchSync(action: KissAction<any>): void;
792
+ /**
793
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
794
+ * the store state. It returns the same list of actions, so that you can instantiate them
795
+ * inline, but still get a list of them.
796
+ *
797
+ * ```ts
798
+ * let actions = store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
799
+ * ```
800
+ *
801
+ * See also:
802
+ * - `dispatch` which dispatches both sync and async actions.
803
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
804
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
805
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
806
+ */
807
+ dispatchAll(actions: KissAction<any>[]): KissAction<any>[];
808
+ /**
809
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
810
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
811
+ * ALL actions finish, with the same list of actions.
812
+ *
813
+ * ```ts
814
+ * let actions = await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
815
+ * ```
816
+ *
817
+ * Note: While the state change from the action's reducers will have been applied when the
818
+ * Promise resolves, other independent processes that the action may have started may still
819
+ * be in progress.
820
+ *
821
+ * If some actions fail with an error that is not swallowed (see `dispatchAndWait`), all
822
+ * actions are still dispatched and allowed to finish. Only then the Promise rejects, with
823
+ * the error of the first failed action in the list.
824
+ *
825
+ * See also:
826
+ * - `dispatch` which dispatches both sync and async actions.
827
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
828
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
829
+ * - `dispatchAll` which dispatches all given actions in parallel.
830
+ */
831
+ dispatchAndWaitAll(actions: KissAction<any>[]): Promise<KissAction<any>[]>;
832
+ /**
833
+ * Returns a promise which will resolve when the given state `condition` is true.
834
+ * If the condition is already true when the method is called, the promise resolves immediately.
835
+ *
836
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
837
+ * is not met in `timeoutMillis` milliseconds, the promise rejects with a `TimeoutException`,
838
+ * and the condition stops being checked. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
839
+ * (or -1, or `Infinity`):
840
+ *
841
+ * ```ts
842
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 }); // 1 second.
843
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 0 }); // No timeout.
844
+ * ```
845
+ *
846
+ * To handle the timeout, you can catch the `TimeoutException`:
847
+ *
848
+ * ```ts
849
+ * try { await store.waitCondition(condition, { timeoutMillis: 5000 }); }
850
+ * catch (error) { if (error instanceof TimeoutException) { ... } else throw error; }
851
+ * ```
852
+ *
853
+ * Or, you can pass an `onTimeout` callback. If the timeout expires, `onTimeout` is called,
854
+ * and the promise resolves with `null` instead of rejecting. If `onTimeout` throws, the
855
+ * promise rejects with that error:
856
+ *
857
+ * ```ts
858
+ * await store.waitCondition(condition, { timeoutMillis: 5000, onTimeout: () => { ... } });
859
+ * ```
860
+ *
861
+ * It returns the action which changed the store state into the condition, in case you need it:
862
+ *
863
+ * ```ts
864
+ * let action = await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
865
+ * ```
866
+ *
867
+ * This method is also eventually useful in production code, but note that while it waits,
868
+ * the condition runs on EVERY state change. A few short-lived waits are fine. But many waits,
869
+ * or waits that may never complete (especially with no timeout), add a cost to every state
870
+ * change, for as long as the store lives, since there is no way to cancel a wait. In
871
+ * production, it's often better to put the logic in an action, or to react to the selected
872
+ * state in your components.
873
+ *
874
+ * Example, in a component:
875
+ *
876
+ * ```tsx
877
+ * function BuyButton() {
878
+ * const store = useStore();
879
+ *
880
+ * async function buy() {
881
+ * store.dispatch(new BuyStock('IBM'));
882
+ * await store.waitCondition((state) => state.portfolio.includes('IBM'), { timeoutMillis: 5000 });
883
+ * showMessage('IBM is now in your portfolio.');
884
+ * }
885
+ *
886
+ * return <button onClick={buy}>Buy IBM</button>;
887
+ * }
888
+ * ```
889
+ *
890
+ * Note `useStore()` doesn't give you the state. To read the state in a component, use
891
+ * `useSelect`. In tests, use the store itself (see `Store.waitCondition`).
892
+ *
893
+ * See also:
894
+ * - `waitCondition` - Waits until the state is in a given condition.
895
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
896
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
897
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
898
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
899
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
900
+ */
901
+ waitCondition(condition: (state: St) => boolean, { timeoutMillis, onTimeout, }: {
902
+ timeoutMillis: number;
903
+ onTimeout?: () => void;
904
+ }): Promise<KissAction<St> | null>;
905
+ /**
906
+ * Returns a Promise that resolves when some actions meet the given `condition`.
907
+ *
908
+ * If `completeImmediately` is false (the default), this method will throw an error if the
909
+ * condition was already true when the method was called. Otherwise, the promise will complete
910
+ * immediately and throw no error.
911
+ *
912
+ * The `condition` is a function that takes the set of actions "in progress", as well as an
913
+ * action that just entered the set (by being dispatched) or left the set (by finishing
914
+ * dispatching). The function should return `true` when the condition is met, and `false`
915
+ * otherwise. For example:
916
+ *
917
+ * ```ts
918
+ * let action = await store.waitActionCondition((actionsInProgress, triggerAction) => { ... });
919
+ * ```
920
+ *
921
+ * Important: Your condition function should NOT modify the set of actions.
922
+ *
923
+ * You get back the set of the actions being dispatched that met the condition, as well as
924
+ * the action that triggered the condition by being added or removed from the set.
925
+ *
926
+ * Note: The condition is only checked when some action is dispatched or finishes dispatching.
927
+ * It's not checked every time action statuses change.
928
+ *
929
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
930
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
931
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
932
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
933
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
934
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
935
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
936
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
937
+ *
938
+ * Example, in a component:
939
+ *
940
+ * ```tsx
941
+ * function RefreshButton() {
942
+ * const store = useStore();
943
+ *
944
+ * async function refresh() {
945
+ * store.dispatch(new RefreshPrices());
946
+ *
947
+ * // Waits until no RefreshPrices action is in progress.
948
+ * await store.waitActionCondition(
949
+ * (actions) => ![...actions].some((action) => action instanceof RefreshPrices),
950
+ * { timeoutMillis: 5000 });
951
+ *
952
+ * showMessage('Prices refreshed.');
953
+ * }
954
+ *
955
+ * return <button onClick={refresh}>Refresh</button>;
956
+ * }
957
+ * ```
958
+ *
959
+ * See also:
960
+ * - `waitCondition` - Waits until the state is in a given condition.
961
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
962
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
963
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
964
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
965
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
966
+ */
967
+ waitActionCondition(condition: (actions: Set<KissAction<St>>, triggerAction: KissAction<St> | null) => boolean, { completeImmediately, timeoutMillis, onTimeout, }?: {
968
+ completeImmediately?: boolean;
969
+ timeoutMillis?: number | null;
970
+ onTimeout?: () => void;
971
+ }): Promise<{
972
+ actions: Set<KissAction<St>>;
973
+ triggerAction: KissAction<St> | null;
974
+ }>;
975
+ /**
976
+ * Returns a promise that resolves when ALL given actions finished dispatching.
977
+ *
978
+ * If `completeImmediately` is false (the default), this method will throw an error if none
979
+ * of the given actions are in progress when the method is called. Otherwise, the promise will
980
+ * complete immediately and throw no error.
981
+ *
982
+ * However, if you don't provide any actions (empty list or `null`), the promise will complete
983
+ * when ALL current actions in progress finish dispatching. In other words, when no actions are
984
+ * currently in progress. In this case, if [completeImmediately] is `false`, the method will
985
+ * throw an error if no actions are in progress when the method is called.
986
+ *
987
+ * Note: Waiting until no actions are in progress should only be done in test, never in
988
+ * production, as it's very easy to create a deadlock. However, waiting for specific actions to
989
+ * finish is safe in production, as long as you're waiting for actions you just dispatched.
990
+ *
991
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
992
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
993
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
994
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
995
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
996
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
997
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
998
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
999
+ *
1000
+ * Example, in a component:
1001
+ *
1002
+ * ```tsx
1003
+ * function BuyBothButton() {
1004
+ * const store = useStore();
1005
+ *
1006
+ * async function buyBoth() {
1007
+ * const buyIBM = new BuyStock('IBM');
1008
+ * const buyTSLA = new BuyStock('TSLA');
1009
+ * store.dispatch(buyIBM);
1010
+ * store.dispatch(buyTSLA);
1011
+ * await store.waitAllActions([buyIBM, buyTSLA]);
1012
+ * showMessage('Done.');
1013
+ * }
1014
+ *
1015
+ * return <button onClick={buyBoth}>Buy IBM and TSLA</button>;
1016
+ * }
1017
+ * ```
1018
+ *
1019
+ * See also:
1020
+ * - `waitCondition` - Waits until the state is in a given condition.
1021
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1022
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1023
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1024
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1025
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1026
+ */
1027
+ waitAllActions(actions: KissAction<St>[] | null, { completeImmediately, timeoutMillis, onTimeout, }?: {
1028
+ completeImmediately?: boolean;
1029
+ timeoutMillis?: number | null;
1030
+ onTimeout?: () => void;
1031
+ }): Promise<{
1032
+ actions: Set<KissAction<St>>;
1033
+ triggerAction: KissAction<St> | null;
1034
+ }>;
1035
+ /**
1036
+ * Returns a promise that completes when an action of the given type in NOT in progress
1037
+ * (it's not being dispatched):
1038
+ *
1039
+ * - If NO action of the given type is currently in progress when the method is called,
1040
+ * and `completeImmediately` is false (the default), this method will throw an error.
1041
+ *
1042
+ * - If NO action of the given type is currently in progress when the method is called,
1043
+ * and `completeImmediately` is true, the promise completes immediately, returns `null`,
1044
+ * and throws no error.
1045
+ *
1046
+ * - If an action of the given type is in progress, the promise completes when the action
1047
+ * finishes, and returns the action. You can use the returned action to check its `status`:
1048
+ *
1049
+ * ```ts
1050
+ * let action = await store.waitActionType(MyAction);
1051
+ * expect(action?.status.originalError).toBeInstanceOf(UserException);
1052
+ * ```
1053
+ *
1054
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1055
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1056
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1057
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1058
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1059
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1060
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1061
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1062
+ *
1063
+ * You should only use this method in tests. In tests you usually have the store itself,
1064
+ * so see the same method in `Store`, which has more examples.
1065
+ *
1066
+ * See also:
1067
+ * - `waitCondition` - Waits until the state is in a given condition.
1068
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1069
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1070
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1071
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1072
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1073
+ */
1074
+ waitActionType(actionType: {
1075
+ new (...args: any[]): KissAction<St>;
1076
+ }, { completeImmediately, timeoutMillis, onTimeout, }?: {
1077
+ completeImmediately?: boolean;
1078
+ timeoutMillis?: number | null;
1079
+ onTimeout?: () => void;
1080
+ }): Promise<KissAction<St> | null>;
1081
+ /**
1082
+ * Returns a promise that completes when ALL actions of the given type are NOT in progress
1083
+ * (none of them is being dispatched):
1084
+ *
1085
+ * - If NO action of the given types is currently in progress when the method is called,
1086
+ * and `completeImmediately` is false (the default), this method will throw an error.
1087
+ *
1088
+ * - If NO action of the given type is currently in progress when the method is called,
1089
+ * and `completeImmediately` is true, the promise completes immediately and throws no error.
1090
+ *
1091
+ * - If any action of the given types is in progress, the promise completes only when
1092
+ * no action of the given types is in progress anymore.
1093
+ *
1094
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1095
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1096
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1097
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1098
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1099
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1100
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1101
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1102
+ *
1103
+ * You should only use this method in tests. In tests you usually have the store itself,
1104
+ * so see the same method in `Store`, which has more examples.
1105
+ *
1106
+ * See also:
1107
+ * - `waitCondition` - Waits until the state is in a given condition.
1108
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1109
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1110
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1111
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1112
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1113
+ */
1114
+ waitAllActionTypes(actionTypes: {
1115
+ new (...args: any[]): KissAction<any>;
1116
+ }[], { completeImmediately, timeoutMillis, onTimeout, }?: {
1117
+ completeImmediately?: boolean;
1118
+ timeoutMillis?: number | null;
1119
+ onTimeout?: () => void;
1120
+ }): Promise<void>;
1121
+ /**
1122
+ * Returns a promise which will complete when ANY action of the given types FINISHES
1123
+ * dispatching. IMPORTANT: This method is different from the other similar methods, because
1124
+ * it does NOT complete immediately if no action of the given types is in progress. Instead,
1125
+ * it waits until an action of the given types finishes dispatching, even if they
1126
+ * were not yet in progress when the method was called.
1127
+ *
1128
+ * This method returns the action that completed the promise, which you can use to check
1129
+ * its `status`.
1130
+ *
1131
+ * It's useful when the actions you are waiting for are not yet dispatched when you call this
1132
+ * method. For example, suppose action `StartAction` starts a process that takes some time
1133
+ * to run and then dispatches an action called `MyFinalAction`. You can then write:
1134
+ *
1135
+ * ```ts
1136
+ * store.dispatch(new StartAction());
1137
+ * let action = await store.waitAnyActionTypeFinishes([MyFinalAction]);
1138
+ * expect(action.status.originalError).toBeInstanceOf(UserException);
1139
+ * ```
1140
+ *
1141
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1142
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1143
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1144
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1145
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1146
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1147
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1148
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1149
+ *
1150
+ * You should only use this method in tests. In tests you usually have the store itself,
1151
+ * so see the same method in `Store`, which has more examples.
1152
+ *
1153
+ * See also:
1154
+ * - `waitCondition` - Waits until the state is in a given condition.
1155
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1156
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1157
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1158
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1159
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1160
+ */
1161
+ waitAnyActionTypeFinishes(actionTypes: {
1162
+ new (...args: any[]): KissAction<St>;
1163
+ }[], options?: {
1164
+ timeoutMillis?: number | null;
1165
+ onTimeout?: undefined;
1166
+ }): Promise<KissAction<St>>;
1167
+ waitAnyActionTypeFinishes(actionTypes: {
1168
+ new (...args: any[]): KissAction<St>;
1169
+ }[], options: {
1170
+ timeoutMillis?: number | null;
1171
+ onTimeout?: () => void;
1172
+ }): Promise<KissAction<St> | null>;
1173
+ }
1174
+ export {};
838
1175
  //# sourceMappingURL=Hooks.d.ts.map