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
@@ -0,0 +1,1446 @@
1
+ 'use client';
2
+ import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from 'react';
3
+ import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';
4
+ import { StoreException } from './StoreException.mjs';
5
+ import { StoreContext } from './StoreProvider.mjs';
6
+ import { EvtState } from './Evt.mjs';
7
+ // How the hooks connect to the store
8
+ //
9
+ // The hooks that read the store use React's `useSyncExternalStore`, which gets two functions
10
+ // from the store: one to subscribe to changes, and one to read the current value (the
11
+ // "snapshot"). The store only tells React that something may have changed; React then reads the
12
+ // snapshot again, compares it with the one it rendered, and renders the component only if it
13
+ // changed. React also reads the snapshot again before committing a render that it started and
14
+ // paused (a transition), and restarts the render if the store changed meanwhile, so a screen
15
+ // never shows parts of two different states at the same time.
16
+ //
17
+ // - `useSelect`, `useObject` and `useAllState` use the React team's `useSyncExternalStoreWithSelector`,
18
+ // whose snapshot is the whole (immutable) state, and whose selector picks a part of it. It
19
+ // keeps the last selected value, and compares the new one with it (`Object.is` for `useSelect`,
20
+ // value by value for `useObject`), so an unchanged selection doesn't render the component.
21
+ //
22
+ // - `useIsWaiting`, `useIsFailed` and `useExceptionFor` read a boolean or an exception from the
23
+ // store, and subscribe to the status changes of the actions. `useIsStoreReady` reads a boolean
24
+ // and subscribes to the readiness. `useSuspense` reads, with the same subscription, a stable
25
+ // promise (while the action runs) or the failure, and throws it.
26
+ //
27
+ // What this means for your selectors: they must be pure, and must not depend on how many times
28
+ // they are called. React may call them more than once per render, and may throw a render away.
29
+ // Store-driven renders are synchronous for React (even inside `startTransition`): they are not
30
+ // deferred like local-state transitions. Async actions are still async; this only says how React
31
+ // schedules the render after the state changes.
32
+ /**
33
+ * Returns a part of the store state:
34
+ *
35
+ * ```ts
36
+ * const name = useSelect((state: State) => state.user.name);
37
+ * ```
38
+ *
39
+ * The component will rebuild only when the `name` changes, ignoring the
40
+ * change in other parts of the state. The selected value is compared with
41
+ * the previous one using `Object.is`, like React does. So `NaN` is equal
42
+ * to `NaN`, but `0` is different from `-0`.
43
+ *
44
+ * The selector must be pure: it must only read its `state` parameter, and return the same
45
+ * value for the same state. It may be an inline function, and may use props and local state.
46
+ * It should return a part of the state, not a new object: a new object is never `Object.is`
47
+ * the previous one, so the component would rebuild for every state change. Use `useObject`
48
+ * for that.
49
+ *
50
+ * Note: You can use `useSelect` and `useSelector` interchangeably.
51
+ * Prefer `useSelect` because it's shorter.
52
+ */
53
+ export function useSelect(selector) {
54
+ const { store, getServerState } = useStoreContext();
55
+ return useSyncExternalStoreWithSelector(store._subscribeState, store._getState, getServerState, selector, Object.is);
56
+ }
57
+ /**
58
+ * Returns a part of the store state:
59
+ *
60
+ * ```ts
61
+ * const name = useSelector((state: State) => state.user.name);
62
+ * ```
63
+ *
64
+ * The component will rebuild only when the `name` changes, ignoring the
65
+ * change in other parts of the state.
66
+ *
67
+ * Note: You can use `useSelect` and `useSelector` interchangeably.
68
+ * Prefer `useSelect` because it's shorter.
69
+ */
70
+ export function useSelector(selector) {
71
+ return useSelect(selector);
72
+ }
73
+ /**
74
+ * Returns an object (or an array, `Map` or `Set`) with some parts of the store state:
75
+ *
76
+ * ```ts
77
+ * const user = useObject((state: State) => ({ name: state.user.name, age: state.user.age }));
78
+ * return <div>{user.name} is {user.age} years old</div>;
79
+ * ```
80
+ *
81
+ * The component will rebuild only when the `name` or the `age` changes, ignoring the
82
+ * change in other parts of the state.
83
+ *
84
+ * Note: With `useSelect`, the same selector would rebuild the component for ALL state changes,
85
+ * since it creates a new object each time. Instead, `useObject` compares the new object with
86
+ * the previous one, value by value (with `Object.is`). If they have the same values, it
87
+ * returns the previous object, and the component doesn't rebuild. This also works if the
88
+ * selector returns an array: `useObject((state: State) => [state.name, state.age])`, or a
89
+ * `Map` or a `Set`, whose entries are compared in order.
90
+ *
91
+ * Note the values themselves are compared by identity. So, the selector should return parts
92
+ * of the state, and not create new objects or arrays for its values.
93
+ *
94
+ * Only plain objects, arrays, `Map`s and `Set`s are compared value by value. Anything else,
95
+ * like a `Date`, a class instance, or a subclass of `Map` or `Set`, is compared by identity,
96
+ * like `useSelect` does. So, `useObject((state: State) => new Point(state.x, state.y))` would
97
+ * rebuild the component for ALL state changes.
98
+ *
99
+ * For this reason, the selector's type only accepts a plain object, an array, a `Map` or a
100
+ * `Set` (or `null` or `undefined`), and a class instance, a `Date`, a string, a number or a
101
+ * function doesn't compile. Note an object whose type is an `interface` doesn't compile either,
102
+ * since TypeScript can't tell it apart from a class instance. Declare it with `type` instead.
103
+ *
104
+ * While the values are the same, `useObject` keeps returning the object it returned before,
105
+ * so you can use it in the dependencies of an effect, or pass it to a memoized component.
106
+ */
107
+ export function useObject(selector) {
108
+ const { store, getServerState } = useStoreContext();
109
+ return useSyncExternalStoreWithSelector(store._subscribeState, store._getState, getServerState, selector, _shallowEqual);
110
+ }
111
+ // Returns true if `a` and `b` are the same, or are both plain objects, arrays, `Map`s or `Set`s
112
+ // with the same values (compared with `Object.is`). The entries of a `Map` or `Set` must also be
113
+ // in the same order, since that's the order they are rendered in. Other objects, like a `Date`,
114
+ // a class instance, or a subclass of `Map` or `Set`, are only equal if they are the same object,
115
+ // since their values may not be in their own enumerable keys.
116
+ function _shallowEqual(a, b) {
117
+ if (Object.is(a, b))
118
+ return true;
119
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)
120
+ return false;
121
+ if (Array.isArray(a) || Array.isArray(b)) {
122
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
123
+ return false;
124
+ for (let i = 0; i < a.length; i++)
125
+ if (!Object.is(a[i], b[i]))
126
+ return false;
127
+ return true;
128
+ }
129
+ const proto = Object.getPrototypeOf(a);
130
+ if (proto !== Object.getPrototypeOf(b))
131
+ return false;
132
+ if (proto === Map.prototype) {
133
+ const mapA = a, mapB = b;
134
+ if (mapA.size !== mapB.size)
135
+ return false;
136
+ const entriesB = mapB.entries();
137
+ for (const [key, value] of mapA) {
138
+ const [keyB, valueB] = entriesB.next().value;
139
+ if (!Object.is(key, keyB) || !Object.is(value, valueB))
140
+ return false;
141
+ }
142
+ return true;
143
+ }
144
+ if (proto === Set.prototype) {
145
+ const setA = a, setB = b;
146
+ if (setA.size !== setB.size)
147
+ return false;
148
+ const valuesB = setB.values();
149
+ for (const value of setA)
150
+ if (!Object.is(value, valuesB.next().value))
151
+ return false;
152
+ return true;
153
+ }
154
+ if (proto !== Object.prototype && proto !== null)
155
+ return false;
156
+ const keysA = Object.keys(a);
157
+ const keysB = Object.keys(b);
158
+ if (keysA.length !== keysB.length)
159
+ return false;
160
+ for (const key of keysA) {
161
+ if (!Object.prototype.hasOwnProperty.call(b, key))
162
+ return false;
163
+ if (!Object.is(a[key], b[key]))
164
+ return false;
165
+ }
166
+ return true;
167
+ }
168
+ /**
169
+ * Returns the whole store state:
170
+ *
171
+ * ```ts
172
+ * const state = useAllState<State>();
173
+ * const name = state.user.name;
174
+ * ```
175
+ *
176
+ * While that's convenient, the above code will rebuild the component for all state changes,
177
+ * no matter if the name changed or not. For this reason, prefer `useSelector`:
178
+ *
179
+ * ```ts
180
+ * const name = useSelector((state: State) => state.user.name);
181
+ * ```
182
+ *
183
+ * Now it will rebuild only when the name changes.
184
+ */
185
+ export function useAllState() {
186
+ return useSelect((state) => state);
187
+ }
188
+ /**
189
+ * Returns an object with all the dispatch and wait methods of the store:
190
+ *
191
+ * - `dispatch` - Dispatches an action, to potentially change the state.
192
+ * - `dispatchAndWait` - Dispatches an action and returns a promise that resolves when the action finishes.
193
+ * - `dispatchSync` - Same as the regular dispatch, except it throws an error if the action is ASYNC.
194
+ * - `dispatchWhen` - Waits until the state is in a given condition, and then dispatches an action.
195
+ * - `dispatchAll` - Dispatches all given actions in parallel.
196
+ * - `dispatchAndWaitAll` - Dispatches all given actions, and returns a promise that resolves when they all finish.
197
+ * - `waitCondition` - Waits until the state is in a given condition.
198
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
199
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
200
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
201
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
202
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
203
+ *
204
+ * Example:
205
+ *
206
+ * ```js
207
+ * const store = useStore();
208
+ * store.dispatch(new MyAction());
209
+ * await store.dispatchAndWait(new MyAction());
210
+ * store.dispatchSync(new MyAction());
211
+ * store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
212
+ * await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
213
+ * await store.waitCondition((state) => state.user.name === "Bill", { timeoutMillis: 1000 });
214
+ * await store.waitAllActionTypes([BuyAction, SellAction]);
215
+ * ```
216
+ *
217
+ * The methods also work when destructured: `const { dispatch, dispatchAndWait } = useStore();`.
218
+ *
219
+ * The object also has `store`, which is the store itself, with its `state` and all its other
220
+ * methods:
221
+ *
222
+ * ```js
223
+ * const { store } = useStore();
224
+ * console.log(store.actionsInProgress());
225
+ * ```
226
+ *
227
+ * IMPORTANT: `useStore` doesn't make the component re-render when the state changes. So, read
228
+ * `store.state` only in event handlers, effects and callbacks, never to render the component.
229
+ * To render it, use the hooks that re-render the component when needed:
230
+ * - To get the state: `useSelect`, `useObject` or `useAllState`
231
+ * - To know if actions are running: `useIsWaiting`
232
+ * - To deal with exceptions: `useIsFailed`, `useExceptionFor` and `useClearExceptionFor`
233
+ * - To use `<Suspense>` and error boundaries instead: `useSuspense`
234
+ *
235
+ * See also:
236
+ * - `useDispatch()` - Hook equivalent to `useStore().dispatch`
237
+ * - `useDispatchAndWait` - Hook equivalent to `useStore().dispatchAndWait`
238
+ * - `useDispatchSync` - Hook equivalent to `useStore().dispatchSync`
239
+ * - `useDispatchWhen` - Hook equivalent to `useStore().dispatchWhen`
240
+ * - `useDispatchAll` - Hook equivalent to `useStore().dispatchAll`
241
+ * - `useDispatchAndWaitAll` - Hook equivalent to `useStore().dispatchAndWaitAll`
242
+ * - `useStoreEffect` - To dispatch actions when the component mounts, when some values change,
243
+ * and when it unmounts.
244
+ */
245
+ export function useStore() {
246
+ const store = useStoreFromContext();
247
+ return useMemo(() => new StoreDispatchers(store), [store]);
248
+ }
249
+ /**
250
+ * @deprecated Use `useDispatch`. Note you also have `useDispatchAndWait` and `useDispatchSync`.
251
+ */
252
+ export function useDispatcher() {
253
+ return useDispatch();
254
+ }
255
+ /**
256
+ * Returns a function that dispatches an action, to potentially change the state:
257
+ *
258
+ * ```ts
259
+ * const dispatch = useDispatch();
260
+ * dispatch(new MyAction());
261
+ * ```
262
+ *
263
+ * This also works:
264
+ *
265
+ * ```ts
266
+ * const store = useStore();
267
+ * store.dispatch(new MyAction());
268
+ * ```
269
+ *
270
+ * To dispatch actions when the component mounts, when some values change, and when it
271
+ * unmounts, see `useStoreEffect`.
272
+ *
273
+ * See also:
274
+ * - `dispatchAll` which dispatches all given actions in parallel.
275
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
276
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
277
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
278
+ */
279
+ export function useDispatch() {
280
+ const store = useStoreFromContext();
281
+ return useMemo(() => store.dispatch.bind(store), [store]);
282
+ }
283
+ /**
284
+ * Use `useStoreEffect` instead of a `useEffect` to dispatch actions when the component mounts
285
+ * (`onMount`), when some values change (`deps` and `onDepsChange`), and when it unmounts
286
+ * (`onUnmount`):
287
+ *
288
+ * ```tsx
289
+ * useStoreEffect({
290
+ * deps: userId,
291
+ * onMount: (store) => store.dispatch(new LoadUser(userId)),
292
+ * onDepsChange: (store, oldUserId) => {
293
+ * store.dispatch(new StopListening(oldUserId));
294
+ * store.dispatch(new LoadUser(userId));
295
+ * },
296
+ * onUnmount: (store) => store.dispatch(new CleanResources()),
297
+ * });
298
+ * ```
299
+ *
300
+ * If `deps` is an array, `onDepsChange` gets the old array:
301
+ *
302
+ * ```tsx
303
+ * useStoreEffect({
304
+ * deps: [userId, filter],
305
+ * onMount: (store) => store.dispatch(new LoadUser(userId, filter)),
306
+ * onDepsChange: (store, [oldUserId, oldFilter]) => {
307
+ * if (userId !== oldUserId) {
308
+ * store.dispatch(new StopListening(oldUserId));
309
+ * store.dispatch(new LoadUser(userId, filter));
310
+ * }
311
+ * else if (filter !== oldFilter) store.dispatch(new ApplyFilter(filter));
312
+ * },
313
+ * });
314
+ * ```
315
+ *
316
+ * All of them are optional, and get the store, so you can use any of its dispatch methods,
317
+ * and read its current `state`. They may be async. To type the state, type the store:
318
+ * `onMount: (store: Store<State>) => ...`. The hook returns nothing. To also dispatch actions
319
+ * from event handlers, use `useDispatch`, `useStore`, etc.
320
+ *
321
+ * Note you can still dispatch actions from a `useEffect`, as usual, if you prefer.
322
+ * `useStoreEffect` is just more convenient, because:
323
+ *
324
+ * - They only run after the store is ready (see `useIsStoreReady`). If the store is not ready
325
+ * when the component mounts, `onMount` is called as soon as it is. If the component unmounts
326
+ * before that, none of them is called.
327
+ *
328
+ * - They are called in order: `onMount`, then `onDepsChange` (any number of times), then
329
+ * `onUnmount`. But if one of them is async, it's not awaited (see below).
330
+ * `onMount` and `onUnmount` run once, even in React's `StrictMode`, which mounts components
331
+ * twice during development. And `onDepsChange` runs once per change.
332
+ *
333
+ * - Like a `useEffect` cleanup, `onUnmount` runs when the component unmounts, before the
334
+ * `onMount` of a component mounted in the same render (in a route switch, for example).
335
+ *
336
+ * When they run, compared to a `useEffect` (in production and in development):
337
+ *
338
+ * - `onMount` runs at the same time as a `useEffect(..., [])` called in the same place of the
339
+ * component, if the store is ready. If not, it runs when the store becomes ready.
340
+ *
341
+ * - `onDepsChange` runs at the same time as a `useEffect(..., [deps])`, but not after the first
342
+ * render. The deps are compared like React does: each value with `Object.is`.
343
+ *
344
+ * - `onUnmount` runs at the same time as the cleanup of a `useEffect`, with one exception:
345
+ * if the component unmounts in the same synchronous run as its mount (before any microtask),
346
+ * `onUnmount` waits one microtask. This is when `StrictMode` does its fake unmount, so if the
347
+ * component mounts again in that time, `onUnmount` is cancelled, and `onMount` is not called
348
+ * again. A real unmount that soon is rare, but its `onUnmount` also runs one microtask later.
349
+ *
350
+ * - So the actions they dispatch are dispatched at the same time as from a `useEffect`. A sync
351
+ * action changes the state before `onMount`, `onDepsChange` or `onUnmount` returns.
352
+ *
353
+ * - They are not awaited. If one of them is async, the next one may run before it finishes.
354
+ * For example, `onUnmount` may run while an async `onMount` is still waiting for an action.
355
+ *
356
+ * - Their errors are not caught, as in a `useEffect`. A sync error goes to React, which shows
357
+ * the nearest error boundary (except that React 18 doesn't give an error thrown by
358
+ * `onUnmount` while the component unmounts to the boundary: it logs it as an internal React
359
+ * error; React 19 fixed it). A rejected promise is an unhandled promise rejection. And when
360
+ * `onMount` waits for the store to be ready, or `onUnmount` waits a microtask (see above),
361
+ * even a sync error is an unhandled promise rejection. If `onMount` throws a sync error when
362
+ * the component mounts (the store is ready), `onUnmount` is not called, as the cleanup of a
363
+ * `useEffect` whose setup throws.
364
+ *
365
+ * - They are the ones from the latest render, so they see its values.
366
+ *
367
+ * - Some React features disconnect the effects and connect them again, without a real unmount.
368
+ * As for a `useEffect`, this calls `onUnmount` and then `onMount` again. For example, in
369
+ * development, Fast Refresh does it to a component when you edit its code. And `<Activity>`
370
+ * does it when it hides the component and shows it again.
371
+ *
372
+ * - A component can call `useStoreEffect` more than once. They run in the order they are called.
373
+ *
374
+ * Note: Changing `deps` doesn't call `onMount` again. If you want to dispatch the same actions
375
+ * on mount and when `deps` change, call the same function from both `onMount` and
376
+ * `onDepsChange`. Each of them sees the values from the latest render.
377
+ *
378
+ * To reload the data on screen when the user comes back to the tab, or when the internet comes
379
+ * back, use `onFocus` and `onOnline` (and `onBlur` and `onOffline` for the opposite):
380
+ *
381
+ * ```tsx
382
+ * useStoreEffect({
383
+ * onMount: (store) => store.dispatch(new LoadPrices()),
384
+ * onFocus: (store) => store.dispatch(new LoadPrices()),
385
+ * onOnline: (store) => store.dispatch(new LoadPrices()),
386
+ * });
387
+ * ```
388
+ *
389
+ * - They are called on the transitions only (hidden → visible, offline → online, and back),
390
+ * never on mount, and only while the component is mounted and after `onMount` was called
391
+ * (so, after the store is ready). Like the other callbacks, they get the store, see the
392
+ * values of the latest render, and are not awaited.
393
+ *
394
+ * - To only reload when the data is old, give the action a `fresh` period: a focus within the
395
+ * period is then aborted silently. Without `fresh`, the action runs on every focus.
396
+ *
397
+ * - What "focused" and "online" mean comes from the store: `store.isFocused` and
398
+ * `store.isOnline`, with `focusSource` and `onlineSource` in `createStore` to change the
399
+ * defaults (for example, in React Native). In tests, drive them with `store.setFocused()` and
400
+ * `store.setOnline()`.
401
+ *
402
+ * - A component that doesn't give these callbacks doesn't make the store listen to the focus
403
+ * and online sources.
404
+ */
405
+ export function useStoreEffect(options) {
406
+ const store = useStoreFromContext();
407
+ // The options from the latest committed render, so that the callbacks see the latest values.
408
+ // A passive effect is enough: the effects below, which read the ref, run after it in the
409
+ // same commit (effects of a component run in order). A layout effect would also warn on the
410
+ // server with React 18 ("useLayoutEffect does nothing on the server").
411
+ const optionsRef = useRef(options);
412
+ useEffect(() => {
413
+ optionsRef.current = options;
414
+ });
415
+ // The store for which `onMount` was called, or null if it wasn't called (or after `onUnmount`).
416
+ const mountedStoreRef = useRef(null);
417
+ // The deps seen by the last `onMount` or `onDepsChange`.
418
+ const lastDepsRef = useRef(undefined);
419
+ // The `onUnmount` waiting to run. See below why it waits.
420
+ const pendingUnmountRef = useRef(null);
421
+ useEffect(() => {
422
+ // In `StrictMode`, React unmounts and then mounts again right away. This is not a real
423
+ // unmount, so we cancel the `onUnmount` that is waiting to run.
424
+ const pending = pendingUnmountRef.current;
425
+ if (pending !== null && pending.store === store) {
426
+ pending.isCancelled = true;
427
+ pendingUnmountRef.current = null;
428
+ }
429
+ let isActive = true;
430
+ // True until the end of the current synchronous flush. StrictMode's fake unmount happens
431
+ // right after the mount, in the same flush, so only an unmount in that time can be fake.
432
+ let isJustMounted = true;
433
+ Promise.resolve().then(() => isJustMounted = false);
434
+ if (mountedStoreRef.current !== store) {
435
+ const mount = () => {
436
+ if (!isActive)
437
+ return;
438
+ mountedStoreRef.current = store;
439
+ lastDepsRef.current = optionsRef.current?.deps;
440
+ optionsRef.current?.onMount?.(store);
441
+ };
442
+ if (store._isReady)
443
+ mount();
444
+ else
445
+ store.ready().then(mount);
446
+ }
447
+ return () => {
448
+ isActive = false;
449
+ if (mountedStoreRef.current !== store)
450
+ return;
451
+ const unmount = () => {
452
+ if (mountedStoreRef.current === store)
453
+ mountedStoreRef.current = null;
454
+ optionsRef.current?.onUnmount?.(store);
455
+ };
456
+ // A real unmount. Runs `onUnmount` right away, like a `useEffect` cleanup, so that it runs
457
+ // before the `onMount` of a component mounted in the same commit (a route switch, for example).
458
+ if (!isJustMounted) {
459
+ unmount();
460
+ return;
461
+ }
462
+ // It may be StrictMode's fake unmount. Waits a microtask, so that it can be cancelled if
463
+ // this is not a real unmount (see above).
464
+ const pendingUnmount = { store, isCancelled: false };
465
+ pendingUnmountRef.current = pendingUnmount;
466
+ Promise.resolve().then(() => {
467
+ if (pendingUnmount.isCancelled)
468
+ return;
469
+ if (pendingUnmountRef.current === pendingUnmount)
470
+ pendingUnmountRef.current = null;
471
+ unmount();
472
+ });
473
+ };
474
+ }, [store]);
475
+ // After each render, calls `onDepsChange` if the deps changed (only after `onMount` was called).
476
+ useEffect(() => {
477
+ if (mountedStoreRef.current !== store)
478
+ return;
479
+ const deps = optionsRef.current?.deps;
480
+ const oldDeps = lastDepsRef.current;
481
+ if (_depsAreEqual(oldDeps, deps))
482
+ return;
483
+ lastDepsRef.current = deps;
484
+ optionsRef.current?.onDepsChange?.(store, oldDeps);
485
+ });
486
+ // Listens to the focus and online signals of the store, only while some render gave one of
487
+ // their callbacks, so that a component with `onMount` only doesn't start the sources. The
488
+ // callbacks run on the transitions only, and only after `onMount` was called.
489
+ const listensToFocus = !!(options.onFocus || options.onBlur);
490
+ const listensToOnline = !!(options.onOnline || options.onOffline);
491
+ useEffect(() => {
492
+ if (!listensToFocus)
493
+ return;
494
+ return _listenToSignal(store._subscribeFocus, store._getIsFocused, (isFocused) => {
495
+ if (mountedStoreRef.current !== store)
496
+ return;
497
+ if (isFocused)
498
+ optionsRef.current?.onFocus?.(store);
499
+ else
500
+ optionsRef.current?.onBlur?.(store);
501
+ });
502
+ }, [store, listensToFocus]);
503
+ useEffect(() => {
504
+ if (!listensToOnline)
505
+ return;
506
+ return _listenToSignal(store._subscribeOnline, store._getIsOnline, (isOnline) => {
507
+ if (mountedStoreRef.current !== store)
508
+ return;
509
+ if (isOnline)
510
+ optionsRef.current?.onOnline?.(store);
511
+ else
512
+ optionsRef.current?.onOffline?.(store);
513
+ });
514
+ }, [store, listensToOnline]);
515
+ }
516
+ // Subscribes to a boolean signal of the store, and calls `onChange` each time it changes.
517
+ function _listenToSignal(subscribe, get, onChange) {
518
+ let last = get();
519
+ return subscribe(() => {
520
+ const value = get();
521
+ if (value === last)
522
+ return;
523
+ last = value;
524
+ onChange(value);
525
+ });
526
+ }
527
+ // Compares deps like React does: each value with `Object.is`.
528
+ function _depsAreEqual(a, b) {
529
+ if (Array.isArray(a) && Array.isArray(b)) {
530
+ if (a.length !== b.length)
531
+ return false;
532
+ for (let i = 0; i < a.length; i++)
533
+ if (!Object.is(a[i], b[i]))
534
+ return false;
535
+ return true;
536
+ }
537
+ return Object.is(a, b);
538
+ }
539
+ /**
540
+ * Dispatches an action and returns a promise that resolves when the action finishes.
541
+ * While the state change from the action's reducer will have been applied when the promise
542
+ * resolves, other independent processes that the action may have started may still be in
543
+ * progress.
544
+ *
545
+ * Usage:
546
+ * ```ts
547
+ * const dispatchAndWait = useDispatchAndWait();
548
+ * await dispatchAndWait(new MyAction());
549
+ * ```
550
+ *
551
+ * See also:
552
+ * - `dispatch` which dispatches both sync and async actions.
553
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
554
+ * - `dispatchAll` which dispatches all given actions in parallel.
555
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
556
+ */
557
+ export function useDispatchAndWait() {
558
+ const store = useStoreFromContext();
559
+ return useMemo(() => store.dispatchAndWait.bind(store), [store]);
560
+ }
561
+ /**
562
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
563
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
564
+ * ALL actions finish.
565
+ *
566
+ * ```ts
567
+ * const dispatchAndWaitAll = useDispatchAndWaitAll();
568
+ * await dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
569
+ * ```
570
+ *
571
+ * Note: While the state change from the action's reducers will have been applied when the
572
+ * Promise resolves, other independent processes that the action may have started may still
573
+ * be in progress.
574
+ *
575
+ * See also:
576
+ * - `dispatch` which dispatches both sync and async actions.
577
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
578
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
579
+ * - `dispatchAll` which dispatches all given actions in parallel.
580
+ */
581
+ export function useDispatchAndWaitAll() {
582
+ const store = useStoreFromContext();
583
+ return useMemo(() => store.dispatchAndWaitAll.bind(store), [store]);
584
+ }
585
+ /**
586
+ * Waits until the store state meets a certain condition, and then dispatches an action.
587
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
588
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
589
+ * the condition, so no other action can change the state in between.
590
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
591
+ * dispatched one after the other, and each condition is checked again right before its
592
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
593
+ *
594
+ * ```ts
595
+ * const dispatchWhen = useDispatchWhen();
596
+ * dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
597
+ * ```
598
+ *
599
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
600
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
601
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
602
+ * timeout is logged. To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`),
603
+ * but note that while it waits, the condition runs on every state change.
604
+ *
605
+ * ```ts
606
+ * dispatchWhen(
607
+ * new BuyStock('IBM'),
608
+ * (state) => state.stocks.getPrice('IBM') >= 100,
609
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
610
+ * );
611
+ * ```
612
+ *
613
+ * Note: The wait is NOT cancelled when the component unmounts.
614
+ *
615
+ * See also:
616
+ * - `dispatch` which dispatches both sync and async actions.
617
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
618
+ */
619
+ export function useDispatchWhen() {
620
+ const store = useStoreFromContext();
621
+ return useMemo(() => store.dispatchWhen.bind(store), [store]);
622
+ }
623
+ /**
624
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
625
+ * the store state.
626
+ *
627
+ * ```ts
628
+ * const dispatchAll = useDispatchAll();
629
+ * dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
630
+ * ```
631
+ *
632
+ * See also:
633
+ * - `dispatch` which dispatches both sync and async actions.
634
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
635
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
636
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
637
+ */
638
+ export function useDispatchAll() {
639
+ const store = useStoreFromContext();
640
+ return useMemo(() => store.dispatchAll.bind(store), [store]);
641
+ }
642
+ /**
643
+ * Dispatches the given action to the Redux store, to potentially change the state.
644
+ *
645
+ * This is exactly the same as the regular `dispatch`, except for the fact it
646
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
647
+ * if any of its `reduce()` or `before()` methods return a Promise.
648
+ *
649
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
650
+ * action is SYNC, which means the state gets changed right after the dispatch call.
651
+ *
652
+ * See also:
653
+ * - `dispatch` which dispatches both sync and async actions.
654
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
655
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
656
+ * - `dispatchAll` which dispatches all given actions in parallel.
657
+ */
658
+ export function useDispatchSync() {
659
+ const store = useStoreFromContext();
660
+ return useMemo(() => store.dispatchSync.bind(store), [store]);
661
+ }
662
+ /**
663
+ * You can use `isWaiting` and pass it an action `type`:
664
+ * - It returns true if an action of the given type (or of a subclass) is currently being processed.
665
+ * - It returns false if no action of the given type is currently being processed.
666
+ * - This is only useful for ASYNC actions. A SYNC action finishes before `dispatch` returns, so
667
+ * outside of it, `isWaiting` is always `false` for it, and components never see it as `true`.
668
+ *
669
+ * Note an action is ASYNC if it returns a promise from its `before` OR its `reduce` methods.
670
+ *
671
+ * ```ts
672
+ * const isWaiting = useIsWaiting(MyAction);
673
+ * if (isWaiting) { ... } // Show a spinner
674
+ * ```
675
+ *
676
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
677
+ * `KissAction.statusKey`): `useIsWaiting(LoadUser, { statusKey: userId })`.
678
+ */
679
+ export function useIsWaiting(type, options) {
680
+ const store = useStoreFromContext();
681
+ const statusKey = options?.statusKey;
682
+ const getIsWaiting = useCallback(() => store.isWaiting(type, { statusKey }), [store, type, statusKey]);
683
+ return useSyncExternalStore(store._subscribeStatus, getIsWaiting, _returnFalse);
684
+ }
685
+ // On the server and while hydrating, no action is waiting or failed, and the store is ready.
686
+ // See `StoreProviderProps.serverState`.
687
+ const _returnFalse = () => false;
688
+ const _returnNull = () => null;
689
+ const _returnTrue = () => true;
690
+ /**
691
+ * Returns true if the store is ready, and false while it's still loading the persisted state.
692
+ * See `Store.ready()`.
693
+ *
694
+ * You can show the UI before the store is ready, using the initial-state. But dispatching an
695
+ * action before the store is ready throws a `StoreException`. Use this hook to show a loading
696
+ * state, and to disable the buttons that dispatch actions:
697
+ *
698
+ * ```tsx
699
+ * const isReady = useIsStoreReady();
700
+ * if (!isReady) return <Spinner/>;
701
+ * // or: <button disabled={!isReady} onClick={() => dispatch(new AddTodo())}>Add</button>
702
+ * ```
703
+ *
704
+ * A store without a persistor is always ready. Once ready, a store stays ready.
705
+ */
706
+ export function useIsStoreReady() {
707
+ const store = useStoreFromContext();
708
+ return useSyncExternalStore(store._subscribeReady, store._getIsReady, _returnTrue);
709
+ }
710
+ /**
711
+ * Returns true if the app is focused (in the browser, if the document is visible: the user is
712
+ * on the tab that shows the app). See `store.isFocused`. The component re-renders when it
713
+ * changes. On the server, it's always `true`.
714
+ *
715
+ * To dispatch an action when the app is focused again, use `useStoreEffect` with `onFocus`.
716
+ */
717
+ export function useIsFocused() {
718
+ const store = useStoreFromContext();
719
+ return useSyncExternalStore(store._subscribeFocus, store._getIsFocused, _returnTrue);
720
+ }
721
+ /**
722
+ * Returns true if the app is online. See `store.isOnline`. The component re-renders when it
723
+ * changes, so you can show an "offline" banner. On the server, it's always `true`.
724
+ *
725
+ * ```tsx
726
+ * const isOnline = useIsOnline();
727
+ * if (!isOnline) return <Banner>You are offline</Banner>;
728
+ * ```
729
+ *
730
+ * To dispatch an action when the internet comes back, use `useStoreEffect` with `onOnline`.
731
+ */
732
+ export function useIsOnline() {
733
+ const store = useStoreFromContext();
734
+ return useSyncExternalStore(store._subscribeOnline, store._getIsOnline, _returnTrue);
735
+ }
736
+ /**
737
+ * Returns the environment of the store (production, staging, testing, etc), given to
738
+ * `createStore` as `environment`, or `undefined`. For example, to show a debug banner:
739
+ *
740
+ * ```ts
741
+ * const env = useEnvironment<Environment>();
742
+ * if (env !== Environment.production) return <DebugBanner />;
743
+ * ```
744
+ *
745
+ * Give it the type of the environment, as above. It never re-renders the component, since
746
+ * the environment doesn't change while the app runs.
747
+ *
748
+ * See also: `useConfiguration`. There is no hook for the dependencies, since components
749
+ * should usually not need them. In actions, read them with `this.store.environment`,
750
+ * `this.store.configuration` and `this.store.dependencies`.
751
+ */
752
+ export function useEnvironment() {
753
+ return useStoreFromContext().environment;
754
+ }
755
+ /**
756
+ * Returns the configuration of the store (feature flags and other configuration values),
757
+ * created by the `configuration` factory given to `createStore`, or `undefined`. For
758
+ * example, to hide a feature behind a flag:
759
+ *
760
+ * ```ts
761
+ * const config = useConfiguration<Config>();
762
+ * if (config.showAdminConsole) return <AdminConsole />;
763
+ * ```
764
+ *
765
+ * Give it the type of the configuration, as above. It never re-renders the component, since
766
+ * the configuration doesn't change while the app runs.
767
+ *
768
+ * See also: `useEnvironment`.
769
+ */
770
+ export function useConfiguration() {
771
+ return useStoreFromContext().configuration;
772
+ }
773
+ /**
774
+ * Returns true if the given action `type` failed, with any error, not only with a
775
+ * `UserException`. Use `exceptionFor` to get the error, if it was a `UserException`.
776
+ * An error swallowed by `wrapError` or the `errorObserver` (they returned `null`), and
777
+ * an `AbortDispatchException`, don't count as failures.
778
+ * Note: This method uses the EXACT action type. Subtypes are not considered.
779
+ *
780
+ * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see
781
+ * `KissAction.statusKey`): `useIsFailed(LoadUser, { statusKey: userId })`.
782
+ */
783
+ export function useIsFailed(type, options) {
784
+ const store = useStoreFromContext();
785
+ const statusKey = options?.statusKey;
786
+ const getIsFailed = useCallback(() => store.isFailed(type, { statusKey }), [store, type, statusKey]);
787
+ return useSyncExternalStore(store._subscribeStatus, getIsFailed, _returnFalse);
788
+ }
789
+ /**
790
+ * Returns the `UserException` of the `type` that failed. Returns `null` if it didn't fail,
791
+ * or if it failed with an error that is not a `UserException` (in that case, `isFailed` is
792
+ * still true).
793
+ * Note: This method uses the EXACT type in `type`. Subtypes are not considered.
794
+ *
795
+ * The exception is the object the action threw (or the one `wrapError` or the `errorObserver`
796
+ * returned). It's returned as is: don't change it after throwing it, since React compares it
797
+ * by identity to know if the component must rebuild.
798
+ *
799
+ * Pass `{ statusKey }` to get the exception of the failure with that `statusKey` (see
800
+ * `KissAction.statusKey`): `useExceptionFor(LoadUser, { statusKey: userId })`. Without it,
801
+ * if actions with different keys failed, you get the `UserException` of the most recent
802
+ * failure.
803
+ */
804
+ export function useExceptionFor(type, options) {
805
+ const store = useStoreFromContext();
806
+ const statusKey = options?.statusKey;
807
+ const getExceptionFor = useCallback(() => store.exceptionFor(type, { statusKey }), [store, type, statusKey]);
808
+ return useSyncExternalStore(store._subscribeStatus, getExceptionFor, _returnNull);
809
+ }
810
+ /**
811
+ * Removes the exact given action `type` from the list of action types that failed.
812
+ * Note it clears the EXACT given type. Subtypes are not considered.
813
+ *
814
+ * Even if you never call this method explicitly, just dispatching an action already clears that action type
815
+ * from the list of failing action types. But you can call this method explicitly if you want to clear the
816
+ * action type before it's used again.
817
+ *
818
+ * Usage:
819
+ * ```ts
820
+ * const clearExceptionFor = useClearExceptionFor();
821
+ * clearExceptionFor(MyAction);
822
+ * clearExceptionFor(AnotherAction);
823
+ * ```
824
+ *
825
+ * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see
826
+ * `KissAction.statusKey`): `clearExceptionFor(LoadUser, { statusKey: userId })`. Without it,
827
+ * all the failures of the type are cleared, whatever their keys.
828
+ */
829
+ export function useClearExceptionFor() {
830
+ const store = useStoreFromContext();
831
+ return useMemo(() => (type, options) => {
832
+ store.clearExceptionFor(type, options);
833
+ }, [store]);
834
+ }
835
+ /**
836
+ * Suspends the component while an action of the given `type` is in progress, and throws the
837
+ * error to the nearest error boundary if the action failed. It's the alternative to
838
+ * `useIsWaiting` and `useIsFailed` for apps that prefer React's `<Suspense>` and error
839
+ * boundaries, like TanStack Query's `useSuspenseQuery`:
840
+ *
841
+ * ```tsx
842
+ * function UserName({ userId }: { userId: string }) {
843
+ * useSuspense(LoadUser, { statusKey: userId });
844
+ * const user = useSelect((state: State) => state.users[userId]);
845
+ * return <p>{user.name}</p>;
846
+ * }
847
+ *
848
+ * function UserCard({ userId }: { userId: string }) {
849
+ * return (
850
+ * <ErrorBoundary fallback={<p>Loading failed.</p>}>
851
+ * <Suspense fallback={<Spinner />}>
852
+ * <UserName userId={userId} />
853
+ * </Suspense>
854
+ * </ErrorBoundary>
855
+ * );
856
+ * }
857
+ * ```
858
+ *
859
+ * - While an action of the type (or of a subclass, like `useIsWaiting`) is in progress, the
860
+ * hook throws a promise. React stops the render there (the code after the hook doesn't run),
861
+ * shows the `fallback` of the nearest `<Suspense>` above the component, and renders the
862
+ * component again when the action finishes. The promise is the same object on every render
863
+ * while the action runs, and resolves when it finishes.
864
+ * - Otherwise, if the last action of the exact type failed (like `useIsFailed`: with any
865
+ * error, not only a `UserException`), the hook throws that error. The nearest error boundary
866
+ * above the component catches it. The failure stays recorded in the store, like with
867
+ * `useIsFailed`: dispatching the action again clears it (and makes the component suspend),
868
+ * and so does `clearExceptionFor`. So a "retry" button in the boundary should dispatch the
869
+ * action again, and then reset the boundary. Pass `{ throwErrors: false }` to not throw, and
870
+ * use `useIsFailed` or `useExceptionFor` instead.
871
+ * - Otherwise, the hook returns, and the component renders normally.
872
+ *
873
+ * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
874
+ * `KissAction.statusKey`): `useSuspense(LoadUser, { statusKey: userId })`. Without it, the
875
+ * component suspends while any action of the type runs, and throws its most recent failure.
876
+ *
877
+ * On the server and while hydrating, the hook never suspends or throws, like `useIsWaiting`
878
+ * and `useIsFailed` are `false` there (see `StoreProviderProps.serverState`). After hydration,
879
+ * it follows the live store.
880
+ *
881
+ * Note: a component that suspends on its first render is thrown away and rendered again from
882
+ * the start, so its local state (`useState`, `useRef`) is lost. A component that already
883
+ * rendered keeps its state while suspended. This is how React's Suspense works.
884
+ */
885
+ export function useSuspense(type, options) {
886
+ const store = useStoreFromContext();
887
+ const statusKey = options?.statusKey;
888
+ const throwErrors = options?.throwErrors ?? true;
889
+ const getValue = useCallback(() => store._suspenseValue(type, statusKey, throwErrors), [store, type, statusKey, throwErrors]);
890
+ const value = useSyncExternalStore(store._subscribeStatus, getValue, _returnNull);
891
+ if (value === null)
892
+ return;
893
+ if (value instanceof Promise)
894
+ throw value;
895
+ throw value.error;
896
+ }
897
+ /**
898
+ * Handles an event (`Evt` or `EvtState`) from the state, by calling the `callback` with its
899
+ * value, once per event:
900
+ *
901
+ * ```tsx
902
+ * function Feed() {
903
+ * const listRef = useRef<HTMLDivElement>(null);
904
+ * const inputRef = useRef<HTMLInputElement>(null);
905
+ *
906
+ * useEvent((state: State) => state.scrollToTopEvt, () => listRef.current?.scrollTo({ top: 0 }));
907
+ * useEvent((state: State) => state.changeTextEvt, (text) => { inputRef.current!.value = text; });
908
+ * ...
909
+ * }
910
+ * ```
911
+ *
912
+ * Events are for an action to ask the UI to do something once, that is not a state change:
913
+ * scroll a list, clear or focus an input, open a dialog. See `Evt` for how actions create them.
914
+ *
915
+ * The `selector` returns one event from the state (or `null`/`undefined`, to handle nothing).
916
+ * The `callback` runs in an effect, after the render that shows the new state is committed, like
917
+ * a `useEffect` (use `useLayoutEvent` to run it before the browser paints, like a
918
+ * `useLayoutEffect`). It's always the callback of the latest render, so it sees the latest props.
919
+ *
920
+ * For an `Evt`, the callback is called once per event, and then the event is **spent**:
921
+ *
922
+ * - A new event while the component is mounted: fires once.
923
+ * - An event created before the component mounts: fires once, when it mounts.
924
+ * - The component remounts later: doesn't fire, since the event is spent.
925
+ * - Two components use the same event: only the first one fires. Create two events for that.
926
+ * - Unrelated re-renders: doesn't fire.
927
+ * - In React's `StrictMode`, which runs effects twice in development: fires once.
928
+ *
929
+ * For an `EvtState`, the callback is called when the state has a different `EvtState` than the
930
+ * last one the component saw. It fires in every mounted component that uses it, but not when the
931
+ * component mounts or remounts, so events that happen while it's not mounted are missed.
932
+ *
933
+ * The store keeps which events were spent (see `store.isEventSpent`), so the events and the state
934
+ * stay immutable. Nothing is spent during render: React may throw a render away, so a render
935
+ * can't spend the event. That's why there is no way to consume an event in render, only this hook.
936
+ */
937
+ export function useEvent(selector, callback) {
938
+ const handle = useEventHandler(selector);
939
+ useEffect(() => handle(callback), [handle, callback]);
940
+ }
941
+ /**
942
+ * The same as `useEvent`, but the `callback` runs in a layout effect, before the browser paints
943
+ * (like a `useLayoutEffect`). Use it when the UI work would otherwise flicker: a scroll, a focus,
944
+ * a measurement. Like `useLayoutEffect`, it does nothing on the server, and React 18 warns about it
945
+ * there. Prefer `useEvent` when the timing doesn't matter.
946
+ */
947
+ export function useLayoutEvent(selector, callback) {
948
+ const handle = useEventHandler(selector);
949
+ useLayoutEffect(() => handle(callback), [handle, callback]);
950
+ }
951
+ // The implementation of `useEvent` and `useLayoutEvent`. Returns a function that handles the
952
+ // selected event with the given callback, if it wasn't handled yet. The function changes when the
953
+ // event (or the store) changes, so the effects above run it again then. They also run it again
954
+ // when the callback changes (an inline callback changes in every render), which does nothing, as
955
+ // the event is already handled. So it's always the callback of the latest render that handles a
956
+ // new event. Running it twice does nothing, which is what `StrictMode` does with effects.
957
+ function useEventHandler(selector) {
958
+ const store = useStoreFromContext();
959
+ const evt = useSelect(selector);
960
+ // For `EvtState` only: the last event the component saw, starting with the one at mount, so
961
+ // that mounting doesn't fire.
962
+ const lastSeenRef = useRef(evt);
963
+ return useCallback((callback) => {
964
+ if (evt == null)
965
+ return;
966
+ if (evt instanceof EvtState) {
967
+ if (lastSeenRef.current === evt)
968
+ return;
969
+ lastSeenRef.current = evt;
970
+ if (evt._spentAtCreation)
971
+ return;
972
+ callback(evt.value);
973
+ return;
974
+ }
975
+ if (store.isEventSpent(evt))
976
+ return;
977
+ store._spentEvents.add(evt);
978
+ callback(evt.value);
979
+ }, [evt, store]);
980
+ }
981
+ function useStoreContext() {
982
+ const context = useContext(StoreContext);
983
+ if (!context?.store) {
984
+ throw new StoreException('useStore must be used within a StoreProvider');
985
+ }
986
+ return context;
987
+ }
988
+ function useStoreFromContext() {
989
+ return useStoreContext().store;
990
+ }
991
+ /**
992
+ * Helper class that allows us to write:
993
+ *
994
+ * ```js
995
+ * const store = useStore();
996
+ * store.dispatch(new MyAction());
997
+ * store.dispatchSync(new MyAction());
998
+ * await store.dispatchAndWait(new MyAction());
999
+ * store.dispatchAll([new MyAction(), new OtherAction()]);
1000
+ * await store.dispatchAndWaitAll([new MyAction(), new OtherAction()]);
1001
+ * ```
1002
+ */
1003
+ class StoreDispatchers {
1004
+ store;
1005
+ constructor(store) {
1006
+ this.store = store;
1007
+ // Bind the methods, so that they also work when destructured: `const { dispatch } = useStore()`.
1008
+ this.dispatch = this.dispatch.bind(this);
1009
+ this.dispatchWhen = this.dispatchWhen.bind(this);
1010
+ this.dispatchAndWait = this.dispatchAndWait.bind(this);
1011
+ this.dispatchSync = this.dispatchSync.bind(this);
1012
+ this.dispatchAll = this.dispatchAll.bind(this);
1013
+ this.dispatchAndWaitAll = this.dispatchAndWaitAll.bind(this);
1014
+ this.waitCondition = this.waitCondition.bind(this);
1015
+ this.waitActionCondition = this.waitActionCondition.bind(this);
1016
+ this.waitAllActions = this.waitAllActions.bind(this);
1017
+ this.waitActionType = this.waitActionType.bind(this);
1018
+ this.waitAllActionTypes = this.waitAllActionTypes.bind(this);
1019
+ this.waitAnyActionTypeFinishes = this.waitAnyActionTypeFinishes.bind(this);
1020
+ this.abort = this.abort.bind(this);
1021
+ }
1022
+ /**
1023
+ * Aborts all the actions of the given `type` (or of a subclass) that are in progress. Each
1024
+ * one finishes silently: its `abortSignal` is aborted, its result is ignored, and so are its
1025
+ * errors. See `Store.abort`.
1026
+ *
1027
+ * ```tsx
1028
+ * const { abort } = useStore();
1029
+ * <button onClick={() => abort(UploadFile)}>Cancel</button>
1030
+ * ```
1031
+ *
1032
+ * Pass `{ statusKey }` to abort only the actions with that `statusKey`.
1033
+ */
1034
+ abort(type, options) {
1035
+ this.store.abort(type, options);
1036
+ }
1037
+ /**
1038
+ * Dispatches the action to the Redux store, to potentially change the state.
1039
+ */
1040
+ dispatch(action) {
1041
+ return this.store.dispatch(action);
1042
+ }
1043
+ /**
1044
+ * Waits until the store state meets a certain condition, and then dispatches an action.
1045
+ * If the condition is already true, the action is dispatched right away, before `dispatchWhen`
1046
+ * returns. Otherwise, it is dispatched synchronously, right after the state change that meets
1047
+ * the condition, so no other action can change the state in between.
1048
+ * If the same state change meets the condition of several `dispatchWhen`, their actions are
1049
+ * dispatched one after the other, and each condition is checked again right before its
1050
+ * action is dispatched. If an earlier action made it false, it keeps waiting.
1051
+ *
1052
+ * ```ts
1053
+ * store.dispatchWhen(new BuyStock('IBM'), (state) => state.stocks.getPrice('IBM') >= 100, { timeoutMillis: 0 });
1054
+ * ```
1055
+ *
1056
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
1057
+ * is not met in `timeoutMillis` milliseconds, the action is NOT dispatched, and the condition
1058
+ * stops being checked. In this case, `onTimeout` is called if you provided it. Otherwise, the
1059
+ * timeout is logged with `Store.log()`. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
1060
+ * (or -1, or `Infinity`), but note that while it waits, the condition runs on every state change.
1061
+ * A `logOut()` cancels the `dispatchWhen`s that are still waiting: their action is not
1062
+ * dispatched, and their `onTimeout` is not called.
1063
+ *
1064
+ * ```ts
1065
+ * store.dispatchWhen(
1066
+ * new BuyStock('IBM'),
1067
+ * (state) => state.stocks.getPrice('IBM') >= 100,
1068
+ * { timeoutMillis: 60 * 1000, onTimeout: () => console.log('IBM never reached 100.') },
1069
+ * );
1070
+ * ```
1071
+ */
1072
+ dispatchWhen(action, condition, options) {
1073
+ this.store.dispatchWhen(action, condition, options);
1074
+ }
1075
+ /**
1076
+ * Dispatches an action and returns a promise that resolves when the action finishes.
1077
+ * While the state change from the action's reducer will have been applied when the promise
1078
+ * resolves, other independent processes that the action may have started may still be in
1079
+ * progress.
1080
+ *
1081
+ * Usage: `await store.dispatchAndWait(new MyAction())`.
1082
+ */
1083
+ dispatchAndWait(action) {
1084
+ return this.store.dispatchAndWait(action);
1085
+ }
1086
+ /**
1087
+ * Dispatches the given action to the Redux store, to potentially change the state.
1088
+ *
1089
+ * This is exactly the same as the regular `dispatch`, except for the fact it
1090
+ * will throw a `StoreException` if the action is ASYNC. Note an action is ASYNC
1091
+ * if any of its `reduce()` or `before()` methods return a Promise.
1092
+ *
1093
+ * The only use for `dispatchSync` is when you need to guarantee (in runtime) that your
1094
+ * action is SYNC, which means the state gets changed right after the dispatch call.
1095
+ */
1096
+ dispatchSync(action) {
1097
+ return this.store.dispatchSync(action);
1098
+ }
1099
+ /**
1100
+ * Dispatches all given actions in parallel, applying their reducer, and possibly changing
1101
+ * the store state. It returns the same list of actions, so that you can instantiate them
1102
+ * inline, but still get a list of them.
1103
+ *
1104
+ * ```ts
1105
+ * let actions = store.dispatchAll([new BuyAction('IBM'), new SellAction('TSLA')]);
1106
+ * ```
1107
+ *
1108
+ * See also:
1109
+ * - `dispatch` which dispatches both sync and async actions.
1110
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
1111
+ * - `dispatchAndWaitAll` which dispatches all given actions, and returns a Promise.
1112
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
1113
+ */
1114
+ dispatchAll(actions) {
1115
+ return this.store.dispatchAll(actions);
1116
+ }
1117
+ /**
1118
+ * Dispatches all given actions in parallel, applying their reducers, and possibly changing
1119
+ * the store state. The actions may be sync or async. It returns a Promise that resolves when
1120
+ * ALL actions finish, with the same list of actions.
1121
+ *
1122
+ * ```ts
1123
+ * let actions = await store.dispatchAndWaitAll([new BuyAction('IBM'), new SellAction('TSLA')]);
1124
+ * ```
1125
+ *
1126
+ * Note: While the state change from the action's reducers will have been applied when the
1127
+ * Promise resolves, other independent processes that the action may have started may still
1128
+ * be in progress.
1129
+ *
1130
+ * If some actions fail with an error that is not swallowed (see `dispatchAndWait`), all
1131
+ * actions are still dispatched and allowed to finish. Only then the Promise rejects, with
1132
+ * the error of the first failed action in the list.
1133
+ *
1134
+ * See also:
1135
+ * - `dispatch` which dispatches both sync and async actions.
1136
+ * - `dispatchAndWait` which dispatches both sync and async actions, and returns a Promise.
1137
+ * - `dispatchSync` which dispatches sync actions, and throws if the action is async.
1138
+ * - `dispatchAll` which dispatches all given actions in parallel.
1139
+ */
1140
+ dispatchAndWaitAll(actions) {
1141
+ return this.store.dispatchAndWaitAll(actions);
1142
+ }
1143
+ /**
1144
+ * Returns a promise which will resolve when the given state `condition` is true.
1145
+ * If the condition is already true when the method is called, the promise resolves immediately.
1146
+ *
1147
+ * Timeout: You must always give a `timeoutMillis`, since there is no default. If the condition
1148
+ * is not met in `timeoutMillis` milliseconds, the promise rejects with a `TimeoutException`,
1149
+ * and the condition stops being checked. To wait with NO timeout, pass `{ timeoutMillis: 0 }`
1150
+ * (or -1, or `Infinity`):
1151
+ *
1152
+ * ```ts
1153
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 }); // 1 second.
1154
+ * await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 0 }); // No timeout.
1155
+ * ```
1156
+ *
1157
+ * To handle the timeout, you can catch the `TimeoutException`:
1158
+ *
1159
+ * ```ts
1160
+ * try { await store.waitCondition(condition, { timeoutMillis: 5000 }); }
1161
+ * catch (error) { if (error instanceof TimeoutException) { ... } else throw error; }
1162
+ * ```
1163
+ *
1164
+ * Or, you can pass an `onTimeout` callback. If the timeout expires, `onTimeout` is called,
1165
+ * and the promise resolves with `null` instead of rejecting. If `onTimeout` throws, the
1166
+ * promise rejects with that error:
1167
+ *
1168
+ * ```ts
1169
+ * await store.waitCondition(condition, { timeoutMillis: 5000, onTimeout: () => { ... } });
1170
+ * ```
1171
+ *
1172
+ * It returns the action which changed the store state into the condition, in case you need it:
1173
+ *
1174
+ * ```ts
1175
+ * let action = await store.waitCondition((state) => state.name == "Bill", { timeoutMillis: 1000 });
1176
+ * ```
1177
+ *
1178
+ * This method is also eventually useful in production code, but note that while it waits,
1179
+ * the condition runs on EVERY state change. A few short-lived waits are fine. But many waits,
1180
+ * or waits that may never complete (especially with no timeout), add a cost to every state
1181
+ * change, for as long as the store lives, since there is no way to cancel a wait. In
1182
+ * production, it's often better to put the logic in an action, or to react to the selected
1183
+ * state in your components.
1184
+ *
1185
+ * Example, in a component:
1186
+ *
1187
+ * ```tsx
1188
+ * function BuyButton() {
1189
+ * const store = useStore();
1190
+ *
1191
+ * async function buy() {
1192
+ * store.dispatch(new BuyStock('IBM'));
1193
+ * await store.waitCondition((state) => state.portfolio.includes('IBM'), { timeoutMillis: 5000 });
1194
+ * showMessage('IBM is now in your portfolio.');
1195
+ * }
1196
+ *
1197
+ * return <button onClick={buy}>Buy IBM</button>;
1198
+ * }
1199
+ * ```
1200
+ *
1201
+ * Note `useStore()` doesn't give you the state. To read the state in a component, use
1202
+ * `useSelect`. In tests, use the store itself (see `Store.waitCondition`).
1203
+ *
1204
+ * See also:
1205
+ * - `waitCondition` - Waits until the state is in a given condition.
1206
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1207
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1208
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1209
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1210
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1211
+ */
1212
+ waitCondition(condition, { timeoutMillis, onTimeout, }) {
1213
+ return this.store.waitCondition(condition, { timeoutMillis, onTimeout });
1214
+ }
1215
+ /**
1216
+ * Returns a Promise that resolves when some actions meet the given `condition`.
1217
+ *
1218
+ * If `completeImmediately` is false (the default), this method will throw an error if the
1219
+ * condition was already true when the method was called. Otherwise, the promise will complete
1220
+ * immediately and throw no error.
1221
+ *
1222
+ * The `condition` is a function that takes the set of actions "in progress", as well as an
1223
+ * action that just entered the set (by being dispatched) or left the set (by finishing
1224
+ * dispatching). The function should return `true` when the condition is met, and `false`
1225
+ * otherwise. For example:
1226
+ *
1227
+ * ```ts
1228
+ * let action = await store.waitActionCondition((actionsInProgress, triggerAction) => { ... });
1229
+ * ```
1230
+ *
1231
+ * Important: Your condition function should NOT modify the set of actions.
1232
+ *
1233
+ * You get back the set of the actions being dispatched that met the condition, as well as
1234
+ * the action that triggered the condition by being added or removed from the set.
1235
+ *
1236
+ * Note: The condition is only checked when some action is dispatched or finishes dispatching.
1237
+ * It's not checked every time action statuses change.
1238
+ *
1239
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1240
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1241
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1242
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1243
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1244
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1245
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1246
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1247
+ *
1248
+ * Example, in a component:
1249
+ *
1250
+ * ```tsx
1251
+ * function RefreshButton() {
1252
+ * const store = useStore();
1253
+ *
1254
+ * async function refresh() {
1255
+ * store.dispatch(new RefreshPrices());
1256
+ *
1257
+ * // Waits until no RefreshPrices action is in progress.
1258
+ * await store.waitActionCondition(
1259
+ * (actions) => ![...actions].some((action) => action instanceof RefreshPrices),
1260
+ * { timeoutMillis: 5000 });
1261
+ *
1262
+ * showMessage('Prices refreshed.');
1263
+ * }
1264
+ *
1265
+ * return <button onClick={refresh}>Refresh</button>;
1266
+ * }
1267
+ * ```
1268
+ *
1269
+ * See also:
1270
+ * - `waitCondition` - Waits until the state is in a given condition.
1271
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1272
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1273
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1274
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1275
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1276
+ */
1277
+ async waitActionCondition(
1278
+ //
1279
+ /// The condition receives the current actions in progress, and the action that triggered the condition.
1280
+ condition, {
1281
+ // If `completeImmediately` is `false` (the default), this method will throw an error if the
1282
+ // condition is already true when the method is called. Otherwise, the promise will complete
1283
+ // immediately and throw no error.
1284
+ completeImmediately = false,
1285
+ //
1286
+ // The maximum time to wait for the condition to be met. The default is 3 seconds.
1287
+ // To disable the timeout, make it 0 or -1.
1288
+ timeoutMillis = null, onTimeout, } = {}) {
1289
+ return this.store.waitActionCondition(condition, {
1290
+ completeImmediately: completeImmediately,
1291
+ timeoutMillis: timeoutMillis,
1292
+ onTimeout: onTimeout,
1293
+ });
1294
+ }
1295
+ /**
1296
+ * Returns a promise that resolves when ALL given actions finished dispatching.
1297
+ *
1298
+ * If `completeImmediately` is false (the default), this method will throw an error if none
1299
+ * of the given actions are in progress when the method is called. Otherwise, the promise will
1300
+ * complete immediately and throw no error.
1301
+ *
1302
+ * However, if you don't provide any actions (empty list or `null`), the promise will complete
1303
+ * when ALL current actions in progress finish dispatching. In other words, when no actions are
1304
+ * currently in progress. In this case, if [completeImmediately] is `false`, the method will
1305
+ * throw an error if no actions are in progress when the method is called.
1306
+ *
1307
+ * Note: Waiting until no actions are in progress should only be done in test, never in
1308
+ * production, as it's very easy to create a deadlock. However, waiting for specific actions to
1309
+ * finish is safe in production, as long as you're waiting for actions you just dispatched.
1310
+ *
1311
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1312
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1313
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1314
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1315
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1316
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1317
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1318
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1319
+ *
1320
+ * Example, in a component:
1321
+ *
1322
+ * ```tsx
1323
+ * function BuyBothButton() {
1324
+ * const store = useStore();
1325
+ *
1326
+ * async function buyBoth() {
1327
+ * const buyIBM = new BuyStock('IBM');
1328
+ * const buyTSLA = new BuyStock('TSLA');
1329
+ * store.dispatch(buyIBM);
1330
+ * store.dispatch(buyTSLA);
1331
+ * await store.waitAllActions([buyIBM, buyTSLA]);
1332
+ * showMessage('Done.');
1333
+ * }
1334
+ *
1335
+ * return <button onClick={buyBoth}>Buy IBM and TSLA</button>;
1336
+ * }
1337
+ * ```
1338
+ *
1339
+ * See also:
1340
+ * - `waitCondition` - Waits until the state is in a given condition.
1341
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1342
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1343
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1344
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1345
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1346
+ */
1347
+ waitAllActions(actions, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
1348
+ return this.store.waitAllActions(actions, {
1349
+ completeImmediately: completeImmediately,
1350
+ timeoutMillis: timeoutMillis,
1351
+ onTimeout: onTimeout,
1352
+ });
1353
+ }
1354
+ /**
1355
+ * Returns a promise that completes when an action of the given type in NOT in progress
1356
+ * (it's not being dispatched):
1357
+ *
1358
+ * - If NO action of the given type is currently in progress when the method is called,
1359
+ * and `completeImmediately` is false (the default), this method will throw an error.
1360
+ *
1361
+ * - If NO action of the given type is currently in progress when the method is called,
1362
+ * and `completeImmediately` is true, the promise completes immediately, returns `null`,
1363
+ * and throws no error.
1364
+ *
1365
+ * - If an action of the given type is in progress, the promise completes when the action
1366
+ * finishes, and returns the action. You can use the returned action to check its `status`:
1367
+ *
1368
+ * ```ts
1369
+ * let action = await store.waitActionType(MyAction);
1370
+ * expect(action?.status.originalError).toBeInstanceOf(UserException);
1371
+ * ```
1372
+ *
1373
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1374
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1375
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1376
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1377
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1378
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1379
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1380
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1381
+ *
1382
+ * You should only use this method in tests. In tests you usually have the store itself,
1383
+ * so see the same method in `Store`, which has more examples.
1384
+ *
1385
+ * See also:
1386
+ * - `waitCondition` - Waits until the state is in a given condition.
1387
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1388
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1389
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1390
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1391
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1392
+ */
1393
+ async waitActionType(actionType, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
1394
+ return this.store.waitActionType(actionType, {
1395
+ completeImmediately: completeImmediately,
1396
+ timeoutMillis: timeoutMillis,
1397
+ onTimeout: onTimeout,
1398
+ });
1399
+ }
1400
+ /**
1401
+ * Returns a promise that completes when ALL actions of the given type are NOT in progress
1402
+ * (none of them is being dispatched):
1403
+ *
1404
+ * - If NO action of the given types is currently in progress when the method is called,
1405
+ * and `completeImmediately` is false (the default), this method will throw an error.
1406
+ *
1407
+ * - If NO action of the given type is currently in progress when the method is called,
1408
+ * and `completeImmediately` is true, the promise completes immediately and throws no error.
1409
+ *
1410
+ * - If any action of the given types is in progress, the promise completes only when
1411
+ * no action of the given types is in progress anymore.
1412
+ *
1413
+ * Timeout: If the condition is not met in `timeoutMillis` milliseconds, the promise rejects
1414
+ * with a `TimeoutException`, and the condition stops being checked. The default is 3 seconds,
1415
+ * which is shorter than the default test timeout of Jest and Vitest (5 seconds). You can change
1416
+ * it globally with `TimeoutException.defaultTimeoutMillis`.
1417
+ * To wait with NO timeout, pass `{ timeoutMillis: 0 }` (or -1, or `Infinity`).
1418
+ * To handle the timeout without an error, pass an `onTimeout` callback. If the timeout
1419
+ * expires, `onTimeout` is called, and the promise resolves with no trigger action (`null`),
1420
+ * instead of rejecting. If `onTimeout` throws, the promise rejects with that error.
1421
+ *
1422
+ * You should only use this method in tests. In tests you usually have the store itself,
1423
+ * so see the same method in `Store`, which has more examples.
1424
+ *
1425
+ * See also:
1426
+ * - `waitCondition` - Waits until the state is in a given condition.
1427
+ * - `waitActionCondition` - Waits until the actions in progress meet a given condition.
1428
+ * - `waitAllActions` - Waits until the given actions are NOT in progress, or no actions are in progress.
1429
+ * - `waitActionType` - Waits until an action of a given type is NOT in progress.
1430
+ * - `waitAllActionTypes` - Waits until all actions of the given type are NOT in progress.
1431
+ * - `waitAnyActionTypeFinishes` - Waits until ANY action of the given types finish dispatching.
1432
+ */
1433
+ async waitAllActionTypes(actionTypes, { completeImmediately = false, timeoutMillis = null, onTimeout, } = {}) {
1434
+ return this.store.waitAllActionTypes(actionTypes, {
1435
+ completeImmediately: completeImmediately,
1436
+ timeoutMillis: timeoutMillis,
1437
+ onTimeout: onTimeout,
1438
+ });
1439
+ }
1440
+ async waitAnyActionTypeFinishes(actionTypes, { timeoutMillis = null, onTimeout, } = {}) {
1441
+ return this.store.waitAnyActionTypeFinishes(actionTypes, {
1442
+ timeoutMillis: timeoutMillis,
1443
+ onTimeout: onTimeout,
1444
+ });
1445
+ }
1446
+ }