kiss-for-react 2.0.4 → 2.0.6

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.
package/README.md CHANGED
@@ -304,6 +304,19 @@ function UserRow({ userId }: { userId: string }) {
304
304
  }
305
305
  ```
306
306
 
307
+ To show one spinner or one error while any of several actions runs or fails, pass an array.
308
+ `useExceptionFor([LoadUser, LoadPosts])` returns the `UserException` of the first type in
309
+ the array that has one:
310
+
311
+ ```tsx
312
+ const isLoading = useIsWaiting([LoadUser, LoadPosts]);
313
+ const isFailed = useIsFailed([LoadUser, LoadPosts]);
314
+ const error = useExceptionFor([LoadUser, LoadPosts]);
315
+ ```
316
+
317
+ Don't write `useIsWaiting(LoadUser) || useIsWaiting(LoadPosts)`. When the first hook returns
318
+ true, the second one is not called, and that breaks the rules of hooks.
319
+
307
320
  ### Suspense and error boundaries
308
321
 
309
322
  If you prefer React's `<Suspense>` and error boundaries to `isWaiting`/`isFailed` checks,
@@ -330,6 +343,9 @@ function UserCard({ userId }: { userId: string }) {
330
343
  }
331
344
  ```
332
345
 
346
+ When the component needs the result of several actions, pass an array:
347
+ `useSuspense([LoadUser, LoadPosts])` suspends while an action of any of the types runs.
348
+
333
349
  &nbsp;
334
350
 
335
351
  ## Actions can send events to the UI
@@ -545,8 +561,24 @@ class LoadPrices extends Action {
545
561
 
546
562
  Use `checkInternet = { dialog: false }` to fail without a dialog, so you can show the
547
563
  error in your components with `isFailed`. Or use `checkInternet = { abort: true }` to
548
- abort the
549
- action silently, as if it had never been dispatched, without any errors.
564
+ abort the action silently, as if it had never been dispatched, without any errors.
565
+
566
+ To show a different error, override `noInternetException()`:
567
+
568
+ ```tsx
569
+ class LoadPrices extends Action {
570
+ checkInternet = { dialog: true }
571
+
572
+ noInternetException() {
573
+ return new UserException('You are offline. The prices could not be loaded.');
574
+ }
575
+
576
+ async reduce() { ... }
577
+ }
578
+ ```
579
+
580
+ The store checks the internet before it calls the action's `before()` method. So you can
581
+ override `before()` without calling `super.before()`.
550
582
 
551
583
  ### UnlimitedRetryCheckInternet
552
584
 
@@ -619,6 +651,8 @@ useStoreEffect({
619
651
  });
620
652
  ```
621
653
 
654
+ To abort the actions of several types, pass an array: `store.abort([LoadUser, LoadPosts])`.
655
+
622
656
  ### Throttle
623
657
 
624
658
  To prevent an action from running too frequently, you can add a `throttle` property to
package/lib/cjs/Hooks.js CHANGED
@@ -704,10 +704,23 @@ function useDispatchSync() {
704
704
  *
705
705
  * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
706
706
  * `KissAction.statusKey`): `useIsWaiting(LoadUser, { statusKey: userId })`.
707
+ *
708
+ * Pass an array of types to know if an action of ANY of them is being processed:
709
+ *
710
+ * ```ts
711
+ * const isLoading = useIsWaiting([LoadUser, LoadPosts]);
712
+ * ```
713
+ *
714
+ * Use this instead of `useIsWaiting(LoadUser) || useIsWaiting(LoadPosts)`, which breaks the rules
715
+ * of hooks: when the first hook returns true, the second one is not called. An empty array
716
+ * returns false. A `statusKey` applies to all the types in the array.
707
717
  */
708
718
  function useIsWaiting(type, options) {
709
719
  const store = useStoreFromContext();
710
720
  const statusKey = options?.statusKey;
721
+ // An array written inline is a new array in each render, so this callback is also new in each
722
+ // render. That's fine: `useSyncExternalStore` only subscribes again when `subscribe` changes,
723
+ // and it re-renders only when the returned value changes.
711
724
  const getIsWaiting = (0, react_1.useCallback)(() => store.isWaiting(type, { statusKey }), [store, type, statusKey]);
712
725
  return (0, react_1.useSyncExternalStore)(store._subscribeStatus, getIsWaiting, _returnFalse);
713
726
  }
@@ -808,6 +821,9 @@ function useConfiguration() {
808
821
  *
809
822
  * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see
810
823
  * `KissAction.statusKey`): `useIsFailed(LoadUser, { statusKey: userId })`.
824
+ *
825
+ * Pass an array of types to know if ANY of them failed: `useIsFailed([LoadUser, LoadPosts])`.
826
+ * An empty array returns false. A `statusKey` applies to all the types in the array.
811
827
  */
812
828
  function useIsFailed(type, options) {
813
829
  const store = useStoreFromContext();
@@ -829,6 +845,10 @@ function useIsFailed(type, options) {
829
845
  * `KissAction.statusKey`): `useExceptionFor(LoadUser, { statusKey: userId })`. Without it,
830
846
  * if actions with different keys failed, you get the `UserException` of the most recent
831
847
  * failure.
848
+ *
849
+ * Pass an array of types to get the `UserException` of the first type in the array that has
850
+ * one: `useExceptionFor([LoadUser, LoadPosts])`. Put the most important type first. An empty
851
+ * array returns `null`. A `statusKey` applies to all the types in the array.
832
852
  */
833
853
  function useExceptionFor(type, options) {
834
854
  const store = useStoreFromContext();
@@ -854,6 +874,8 @@ function useExceptionFor(type, options) {
854
874
  * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see
855
875
  * `KissAction.statusKey`): `clearExceptionFor(LoadUser, { statusKey: userId })`. Without it,
856
876
  * all the failures of the type are cleared, whatever their keys.
877
+ *
878
+ * Pass an array of types to clear all of them: `clearExceptionFor([LoadUser, LoadPosts])`.
857
879
  */
858
880
  function useClearExceptionFor() {
859
881
  const store = useStoreFromContext();
@@ -903,6 +925,12 @@ function useClearExceptionFor() {
903
925
  * `KissAction.statusKey`): `useSuspense(LoadUser, { statusKey: userId })`. Without it, the
904
926
  * component suspends while any action of the type runs, and throws its most recent failure.
905
927
  *
928
+ * Pass an array of types when the component needs the result of several actions:
929
+ * `useSuspense([LoadUser, LoadPosts])`. The component suspends while an action of ANY of the
930
+ * types runs, and renders again when none of them runs. Then, if any of them failed, it throws
931
+ * the error of the first type in the array that failed. A `statusKey` applies to all the types
932
+ * in the array.
933
+ *
906
934
  * On the server and while hydrating, the hook never suspends or throws, like `useIsWaiting`
907
935
  * and `useIsFailed` are `false` there (see `StoreProviderProps.serverState`). After hydration,
908
936
  * it follows the live store.
@@ -1058,6 +1086,8 @@ class StoreDispatchers {
1058
1086
  * ```
1059
1087
  *
1060
1088
  * Pass `{ statusKey }` to abort only the actions with that `statusKey`.
1089
+ *
1090
+ * Pass an array of types to abort the actions of all of them: `abort([LoadUser, LoadPosts])`.
1061
1091
  */
1062
1092
  abort(type, options) {
1063
1093
  this.store.abort(type, options);
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UserExceptionAction = exports.MergeServerStateAction = exports.UpdateStateAction = exports.ServerPush = exports.OptimisticSyncWithPush = exports.OptimisticSync = exports.OptimisticCommand = exports.ActionStatus = exports.KissAction = exports.Poll = void 0;
4
+ exports._checkNotOverridden = _checkNotOverridden;
4
5
  exports._isSameNonReentrantKey = _isSameNonReentrantKey;
5
6
  const StoreException_1 = require("./StoreException");
6
7
  const UserException_1 = require("./UserException");
@@ -267,8 +268,8 @@ class KissAction {
267
268
  *
268
269
  * Other notes:
269
270
  * - It works with both SYNC and ASYNC reducers. Even SYNC reducers can be affected, when an
270
- * ASYNC `before` (for example, the one of `checkInternet`) makes an older action reach its
271
- * reducer after a newer one was dispatched.
271
+ * ASYNC `before` (or the internet check of `checkInternet`) makes an older action reach
272
+ * its reducer after a newer one was dispatched.
272
273
  * - `store.clearInternalActionProps()` forgets the keys. The actions dispatched after it
273
274
  * don't make the ones dispatched before it old.
274
275
  */
@@ -498,33 +499,43 @@ class KissAction {
498
499
  * This method is useful for actions that need to perform some checks before executing the
499
500
  * reducer. If necessary, it can prevent the reducer from running by throwing an exception.
500
501
  *
501
- * For example, the default `before()` method checks if the `checkInternet` property was set.
502
- * If it was set, it checks if the device has an internet connection. If the connection is not
503
- * present, it throws a `UserException` (or an `AbortDispatchException`, with
504
- * `checkInternet = { abort: true }`), preventing the reducer from running.
502
+ * The default `before()` does nothing, and no Kiss feature uses it. So you don't need to call
503
+ * `super.before()` when you override it. For example, the internet check of `checkInternet`
504
+ * is done by the store, before it calls `before()`.
505
505
  *
506
506
  * Note the `after()` method always runs, even if the `before()` method throws an exception.
507
507
  */
508
508
  before() {
509
- if (this.checkInternet) {
510
- const { dialog, abort } = this.checkInternet;
511
- return this._hasInternet().then((isConnected) => {
512
- if (!isConnected) {
513
- if (abort) {
514
- throw (0, StoreException_1.kissAbort)('No Internet');
515
- }
516
- else if (dialog) {
517
- throw new UserException_1.UserException("Please, verify your connection.").withTitle("There is no Internet");
518
- }
519
- else {
520
- throw new UserException_1.UserException("No Internet").withDialog(false);
521
- }
522
- }
523
- });
524
- }
525
- // Return void (not a Promise) when we don't need to check internet.
526
- else
527
- return;
509
+ }
510
+ /**
511
+ * Returns the error of an action with `checkInternet`, when there is no internet. Override it
512
+ * to show a different error. For example:
513
+ *
514
+ * ```ts
515
+ * class LoadPrices extends Action {
516
+ * checkInternet = { dialog: true };
517
+ *
518
+ * protected noInternetException() {
519
+ * return new UserException('You are offline. The prices could not be loaded.');
520
+ * }
521
+ *
522
+ * async reduce() { ... }
523
+ * }
524
+ * ```
525
+ *
526
+ * The store calls it only when there is no internet, and the `dialog` option of
527
+ * `checkInternet` decides if the returned exception opens a dialog: the store calls
528
+ * `withDialog(dialog)` on it. It's not called with `checkInternet = { abort: true }`, since
529
+ * the action is then aborted silently.
530
+ *
531
+ * By default, it returns a `UserException` with the message "Please, verify your connection."
532
+ * and the title "There is no Internet" (with `dialog: true`), or with the message
533
+ * "No Internet" (with `dialog: false`).
534
+ */
535
+ noInternetException() {
536
+ return this.checkInternet?.dialog
537
+ ? new UserException_1.UserException('Please, verify your connection.').withTitle('There is no Internet')
538
+ : new UserException_1.UserException('No Internet');
528
539
  }
529
540
  /**
530
541
  * Checks if the device has an internet connection, for `checkInternet` and
@@ -546,7 +557,7 @@ class KissAction {
546
557
  *
547
558
  * const store = createStore<State>({
548
559
  * initialState: State.initialState,
549
- * onlineSource: (setOnline) => NetInfo.addEventListener((s) => setOnline(s.isConnected === true)),
560
+ * onlineSource: (setOnline) => NetInfo.addEventListener((s) => setOnline(s.isConnected !== false)),
550
561
  * });
551
562
  * ```
552
563
  *
@@ -556,7 +567,7 @@ class KissAction {
556
567
  *
557
568
  * ```typescript
558
569
  * protected hasInternet(): Promise<boolean> {
559
- * return NetInfo.fetch().then(state => state.isConnected === true);
570
+ * return NetInfo.fetch().then(state => state.isConnected !== false);
560
571
  * }
561
572
  * ```
562
573
  *
@@ -1076,6 +1087,9 @@ class KissAction {
1076
1087
  *
1077
1088
  * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see `statusKey`):
1078
1089
  * `this.isWaiting(LoadUser, { statusKey: userId })`.
1090
+ *
1091
+ * Pass an array of types to know if an action of ANY of them is being processed:
1092
+ * `this.isWaiting([LoadUser, LoadPosts])`.
1079
1093
  */
1080
1094
  isWaiting(type, options) {
1081
1095
  return this.store.isWaiting(type, options);
@@ -1089,6 +1103,8 @@ class KissAction {
1089
1103
  *
1090
1104
  * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see `statusKey`):
1091
1105
  * `this.isFailed(LoadUser, { statusKey: userId })`.
1106
+ *
1107
+ * Pass an array of types to know if ANY of them failed: `this.isFailed([LoadUser, LoadPosts])`.
1092
1108
  */
1093
1109
  isFailed(type, options) {
1094
1110
  return this.store.isFailed(type, options);
@@ -1102,6 +1118,9 @@ class KissAction {
1102
1118
  * Pass `{ statusKey }` to get the exception of the failure with that `statusKey` (see
1103
1119
  * `statusKey`): `this.exceptionFor(LoadUser, { statusKey: userId })`. Without it, if actions
1104
1120
  * with different keys failed, you get the `UserException` of the most recent failure.
1121
+ *
1122
+ * Pass an array of types to get the `UserException` of the first type in the array that has
1123
+ * one: `this.exceptionFor([LoadUser, LoadPosts])`.
1105
1124
  */
1106
1125
  exceptionFor(type, options) {
1107
1126
  return this.store.exceptionFor(type, options);
@@ -1122,6 +1141,8 @@ class KissAction {
1122
1141
  * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see `statusKey`):
1123
1142
  * `this.clearExceptionFor(LoadUser, { statusKey: userId })`. Without it, all the failures of
1124
1143
  * the type are cleared, whatever their keys.
1144
+ *
1145
+ * Pass an array of types to clear all of them: `this.clearExceptionFor([LoadUser, LoadPosts])`.
1125
1146
  */
1126
1147
  clearExceptionFor(type, options) {
1127
1148
  return this.store.clearExceptionFor(type, options);
@@ -3120,6 +3141,7 @@ class OptimisticCommand extends KissAction {
3120
3141
  /**
3121
3142
  * Do NOT override this method. Implement `optimisticValue`, `getValueFromState`,
3122
3143
  * `applyValueToState` and `sendCommandToServer` instead.
3144
+ * If you override it, the dispatch throws a `StoreException`.
3123
3145
  */
3124
3146
  async reduce() {
3125
3147
  // The value to roll back to. It's read now, and not from `initialState`, because the action
@@ -3280,6 +3302,7 @@ class OptimisticCommand extends KissAction {
3280
3302
  */
3281
3303
  _injectStore(_store) {
3282
3304
  super._injectStore(_store);
3305
+ _checkNotOverridden(this, OptimisticCommand, 'an OptimisticCommand', 'reduce', 'Implement `optimisticValue`, `getValueFromState`, `applyValueToState` and `sendCommandToServer` instead.');
3283
3306
  if (this.nonReentrant)
3284
3307
  throw new StoreException_1.StoreException(`Action ${this.constructor.name} is an OptimisticCommand, which is always non-reentrant. ` +
3285
3308
  'Remove its `nonReentrant` property.');
@@ -3758,6 +3781,7 @@ class OptimisticSync extends KissAction {
3758
3781
  /**
3759
3782
  * Do NOT override this method. Implement `valueToApply`, `applyOptimisticValueToState`,
3760
3783
  * `getValueFromState` and `sendValueToServer` instead.
3784
+ * If you override it, the dispatch throws a `StoreException`.
3761
3785
  */
3762
3786
  async reduce() {
3763
3787
  const value = this.valueToApply();
@@ -3854,6 +3878,7 @@ class OptimisticSync extends KissAction {
3854
3878
  */
3855
3879
  _injectStore(_store) {
3856
3880
  super._injectStore(_store);
3881
+ _checkNotOverridden(this, OptimisticSync, 'an OptimisticSync', 'reduce', 'Implement `valueToApply`, `applyOptimisticValueToState`, `getValueFromState` and `sendValueToServer` instead.');
3857
3882
  _checkIncompatibleFeatures(this, 'an OptimisticSync', false);
3858
3883
  }
3859
3884
  }
@@ -4273,6 +4298,7 @@ class OptimisticSyncWithPush extends KissAction {
4273
4298
  /**
4274
4299
  * Do NOT override this method. Implement `valueToApply`, `applyOptimisticValueToState`,
4275
4300
  * `getValueFromState`, `sendValueToServer` and `getServerRevisionFromState` instead.
4301
+ * If you override it, the dispatch throws a `StoreException`.
4276
4302
  */
4277
4303
  async reduce() {
4278
4304
  const key = this._key = this.computeOptimisticSyncKey();
@@ -4412,6 +4438,8 @@ class OptimisticSyncWithPush extends KissAction {
4412
4438
  */
4413
4439
  _injectStore(_store) {
4414
4440
  super._injectStore(_store);
4441
+ _checkNotOverridden(this, OptimisticSyncWithPush, 'an OptimisticSyncWithPush', 'reduce', 'Implement `valueToApply`, `applyOptimisticValueToState`, `getValueFromState`, `sendValueToServer` ' +
4442
+ 'and `getServerRevisionFromState` instead.');
4415
4443
  _checkIncompatibleFeatures(this, 'an OptimisticSyncWithPush', false);
4416
4444
  }
4417
4445
  }
@@ -4557,6 +4585,7 @@ class ServerPush extends KissAction {
4557
4585
  /**
4558
4586
  * Do NOT override this method. Implement `associatedAction`, `pushMetadata`,
4559
4587
  * `applyServerPushToState` and `getServerRevisionFromState` instead.
4588
+ * If you override it, the dispatch throws a `StoreException`.
4560
4589
  */
4561
4590
  reduce() {
4562
4591
  const key = this.computeOptimisticSyncKey();
@@ -4617,10 +4646,29 @@ class ServerPush extends KissAction {
4617
4646
  */
4618
4647
  _injectStore(_store) {
4619
4648
  super._injectStore(_store);
4649
+ _checkNotOverridden(this, ServerPush, 'a ServerPush', 'reduce', 'Implement `associatedAction`, `pushMetadata`, `applyServerPushToState` and `getServerRevisionFromState` instead.');
4620
4650
  _checkIncompatibleFeatures(this, 'a ServerPush', true);
4621
4651
  }
4622
4652
  }
4623
4653
  exports.ServerPush = ServerPush;
4654
+ /**
4655
+ * Throws a `StoreException` if the given action overrides `member` of the Kiss base class
4656
+ * `base` (for example, the `reduce` of an `OptimisticCommand`). The base class uses that member
4657
+ * to do its work, so overriding it would turn the feature off with no error. The `description`
4658
+ * describes the base class (for example, "an OptimisticCommand"), and `hint` says what to do.
4659
+ * For Kiss internal use only.
4660
+ * @internal
4661
+ */
4662
+ function _checkNotOverridden(action, base, description, member, hint) {
4663
+ const has = (obj) => Object.prototype.hasOwnProperty.call(obj, member);
4664
+ // An arrow function property is in the action itself. A method or getter is in the prototype
4665
+ // of the action's class, or of one of its superclasses that extend the base class.
4666
+ let isOverridden = has(action);
4667
+ for (let proto = Object.getPrototypeOf(action); !isOverridden && proto && proto !== base.prototype; proto = Object.getPrototypeOf(proto))
4668
+ isOverridden = has(proto);
4669
+ if (isOverridden)
4670
+ throw new StoreException_1.StoreException(`Action ${action.constructor.name} is ${description}, which must not override \`${member}\`. ${hint}`);
4671
+ }
4624
4672
  /**
4625
4673
  * Throws a `StoreException` if the given action, which is described by `description` (for
4626
4674
  * example, "an OptimisticSync"), uses a feature it can't use. It can only use `checkInternet`,
@@ -154,7 +154,8 @@ exports.Pages = Pages;
154
154
  * - It should not be combined with `nonReentrant` or `ignoreOld`, since it already decides
155
155
  * which loads run. Dispatching it with those throws a `StoreException`.
156
156
  * - To poll a list, override `createPollingAction()` to return a `'refresh'`.
157
- * - Do not override `reduce`, `abortDispatch` or `statusKey`.
157
+ * - Do not override `reduce` or `statusKey` (the dispatch throws a `StoreException`), and an
158
+ * `abortDispatch` override must call `super.abortDispatch()`.
158
159
  */
159
160
  class LoadPages extends KissAction_1.KissAction {
160
161
  constructor(which = 'refresh') {
@@ -180,7 +181,7 @@ class LoadPages extends KissAction_1.KissAction {
180
181
  pagesKeyParams() {
181
182
  return null;
182
183
  }
183
- /** The `statusKey` is `pagesKeyParams()`. Do NOT override this; override `pagesKeyParams()`. */
184
+ /** The `statusKey` is `pagesKeyParams()`. Do NOT override this (the dispatch throws a `StoreException`); override `pagesKeyParams()`. */
184
185
  get statusKey() {
185
186
  return this.pagesKeyParams();
186
187
  }
@@ -216,6 +217,7 @@ class LoadPages extends KissAction_1.KissAction {
216
217
  /**
217
218
  * Do NOT override this method. Implement `getPagesFromState`, `applyPagesToState`,
218
219
  * `initialPageParam`, `loadPage` and `nextPageParam` instead.
220
+ * If you override it, the dispatch throws a `StoreException`.
219
221
  */
220
222
  async reduce() {
221
223
  // A `'first'` or `'refresh'` aborts the other loads of the same list, so that the newest
@@ -309,6 +311,8 @@ class LoadPages extends KissAction_1.KissAction {
309
311
  */
310
312
  _injectStore(_store) {
311
313
  super._injectStore(_store);
314
+ (0, KissAction_1._checkNotOverridden)(this, LoadPages, 'a LoadPages', 'reduce', 'Implement `getPagesFromState`, `applyPagesToState`, `initialPageParam`, `loadPage` and `nextPageParam` instead.');
315
+ (0, KissAction_1._checkNotOverridden)(this, LoadPages, 'a LoadPages', 'statusKey', 'Override `pagesKeyParams()` instead, which is also the `statusKey`.');
312
316
  if (!['first', 'next', 'previous', 'refresh'].includes(this.which))
313
317
  throw new StoreException_1.StoreException(`Action ${this.constructor.name} is a LoadPages with an invalid \`which\`: ${String(this.which)}. ` +
314
318
  `Use 'first', 'next', 'previous' or 'refresh'.`);
package/lib/cjs/Store.js CHANGED
@@ -1368,7 +1368,7 @@ class Store {
1368
1368
  const beforeResult = (async () => {
1369
1369
  if (discarded)
1370
1370
  throw (0, StoreException_1.kissAbort)('Discarded from the sequential queue.');
1371
- return action['before']();
1371
+ return this._runBefore(action);
1372
1372
  })();
1373
1373
  this._runAsyncBeforeOnwards(action, beforeResult).then();
1374
1374
  });
@@ -1768,10 +1768,31 @@ class Store {
1768
1768
  this._notSyncErrors.add(error);
1769
1769
  return error;
1770
1770
  }
1771
+ // Runs the internet check of `checkInternet`, if the action has it, and then the action's
1772
+ // `before`. The check is done here, and not in the default `before`, so that it still works
1773
+ // when the action overrides `before` without calling `super.before()`. If there is no
1774
+ // internet, it throws, and `before` doesn't run. Returns a Promise only if there is an
1775
+ // internet check, or if `before` is async, so that the other actions stay SYNC.
1776
+ _runBefore(action) {
1777
+ const options = action.checkInternet;
1778
+ if (!options)
1779
+ return action['before']();
1780
+ return action._hasInternet().then((isConnected) => {
1781
+ if (!isConnected) {
1782
+ if (options.abort)
1783
+ throw (0, StoreException_1.kissAbort)('No Internet');
1784
+ throw action['noInternetException']().withDialog(!!options.dialog);
1785
+ }
1786
+ return action['before']();
1787
+ });
1788
+ }
1771
1789
  _runFromStart(action, mustBeSync) {
1772
1790
  // A debounced action always waits for its debounce period, so it can't be SYNC.
1773
1791
  if (mustBeSync && action._debounceMillis !== null)
1774
1792
  throw this._notSyncError(`You called dispatchSync(${action.constructor.name}), but the action uses debounce, which makes it ASYNC.`);
1793
+ // The internet check of `checkInternet` is async, so the action can't be SYNC.
1794
+ if (mustBeSync && action.checkInternet)
1795
+ throw this._notSyncError(`You called dispatchSync(${action.constructor.name}), but the action uses checkInternet, which makes it ASYNC.`);
1775
1796
  // A sequential action always waits for its turn in the queue, so it can't be SYNC.
1776
1797
  if (action.sequential) {
1777
1798
  if (mustBeSync)
@@ -1785,9 +1806,9 @@ class Store {
1785
1806
  if (action.ignoreOld && !this._pollSkipsReduce(action))
1786
1807
  this._abortOlderIgnoreOld(action);
1787
1808
  // BEFORE
1788
- // 1) Runs the `before` method.
1809
+ // 1) Runs the `before` method (after the internet check of `checkInternet`, if any).
1789
1810
  // It may be sync or async, but it doesn't return anything.
1790
- const beforeResult = action['before']();
1811
+ const beforeResult = this._runBefore(action);
1791
1812
  // 2) If it's async, wait for the `before` method to finish.
1792
1813
  if (beforeResult instanceof Promise) {
1793
1814
  if (mustBeSync) {
@@ -2625,13 +2646,20 @@ class Store {
2625
2646
  * Pass `{ statusKey }` to abort only the actions with that `statusKey` (see
2626
2647
  * `KissAction.statusKey`): `store.abort(LoadUser, { statusKey: userId })`.
2627
2648
  *
2649
+ * Pass an array of types to abort the actions of all of them. For example, when a screen
2650
+ * closes: `onUnmount: (store) => store.abort([LoadUser, LoadPosts])`. A `statusKey` applies to
2651
+ * all the types in the array.
2652
+ *
2628
2653
  * To abort a single action instance, use its `abort()` method.
2629
2654
  */
2630
2655
  abort(type, options) {
2656
+ const types = _toTypeArray(type);
2631
2657
  const statusKey = options?.statusKey;
2658
+ const name = Array.isArray(type) ? `[${types.map(t => t.name).join(', ')}]` : types[0].name;
2632
2659
  for (const action of this._actionsInProgress) {
2633
- if (action instanceof type && (statusKey === undefined || (0, KissAction_1._isSameNonReentrantKey)(action.statusKey, statusKey)))
2634
- action._abort(`The action was aborted by store.abort(${type.name}).`);
2660
+ if (types.some(t => action instanceof t) &&
2661
+ (statusKey === undefined || (0, KissAction_1._isSameNonReentrantKey)(action.statusKey, statusKey)))
2662
+ action._abort(`The action was aborted by store.abort(${name}).`);
2635
2663
  }
2636
2664
  }
2637
2665
  /**
@@ -2652,11 +2680,17 @@ class Store {
2652
2680
  *
2653
2681
  * Pass `{ statusKey }` to consider only the actions with that `statusKey` (see
2654
2682
  * `KissAction.statusKey`): `store.isWaiting(LoadUser, { statusKey: userId })`.
2683
+ *
2684
+ * Pass an array of types to know if an action of ANY of them is being processed:
2685
+ * `store.isWaiting([LoadUser, LoadPosts])`. An empty array returns false. A `statusKey`
2686
+ * applies to all the types in the array.
2655
2687
  */
2656
2688
  isWaiting(type, options) {
2689
+ const types = _toTypeArray(type);
2657
2690
  const statusKey = options?.statusKey;
2658
2691
  for (const action of this._actionsInProgress) {
2659
- if (action instanceof type && (statusKey === undefined || (0, KissAction_1._isSameNonReentrantKey)(action.statusKey, statusKey))) {
2692
+ if (types.some(t => action instanceof t) &&
2693
+ (statusKey === undefined || (0, KissAction_1._isSameNonReentrantKey)(action.statusKey, statusKey))) {
2660
2694
  return true;
2661
2695
  }
2662
2696
  }
@@ -2671,9 +2705,13 @@ class Store {
2671
2705
  *
2672
2706
  * Pass `{ statusKey }` to consider only the failures with that `statusKey` (see
2673
2707
  * `KissAction.statusKey`): `store.isFailed(LoadUser, { statusKey: userId })`.
2708
+ *
2709
+ * Pass an array of types to know if ANY of them failed:
2710
+ * `store.isFailed([LoadUser, LoadPosts])`. An empty array returns false. A `statusKey`
2711
+ * applies to all the types in the array.
2674
2712
  */
2675
2713
  isFailed(type, options) {
2676
- return this._findFailure(type, options) !== null;
2714
+ return _toTypeArray(type).some(t => this._findFailure(t, options) !== null);
2677
2715
  }
2678
2716
  /**
2679
2717
  * Returns the `UserException` of the `type` that failed. Returns `null` if it didn't fail,
@@ -2685,8 +2723,20 @@ class Store {
2685
2723
  * `KissAction.statusKey`): `store.exceptionFor(LoadUser, { statusKey: userId })`. Without it,
2686
2724
  * if actions with different keys failed, you get the `UserException` of the most recent
2687
2725
  * failure.
2726
+ *
2727
+ * Pass an array of types to get the `UserException` of the first type in the array that has
2728
+ * one: `store.exceptionFor([LoadUser, LoadPosts])`. Put the most important type first. An
2729
+ * empty array returns `null`. A `statusKey` applies to all the types in the array.
2688
2730
  */
2689
2731
  exceptionFor(type, options) {
2732
+ if (Array.isArray(type)) {
2733
+ for (const t of type) {
2734
+ const exception = this.exceptionFor(t, options);
2735
+ if (exception !== null)
2736
+ return exception;
2737
+ }
2738
+ return null;
2739
+ }
2690
2740
  const failures = this._failedActions.get(type);
2691
2741
  if (failures === undefined)
2692
2742
  return null;
@@ -2720,12 +2770,19 @@ class Store {
2720
2770
  * Pass `{ statusKey }` to clear only the failure with that `statusKey` (see
2721
2771
  * `KissAction.statusKey`): `store.clearExceptionFor(LoadUser, { statusKey: userId })`.
2722
2772
  * Without it, all the failures of the type are cleared, whatever their keys.
2773
+ *
2774
+ * Pass an array of types to clear all of them: `store.clearExceptionFor([LoadUser, LoadPosts])`.
2775
+ * The components are updated only once. A `statusKey` applies to all the types in the array.
2723
2776
  */
2724
2777
  clearExceptionFor(type, options) {
2725
2778
  const statusKey = options?.statusKey;
2726
- const removed = (statusKey === undefined)
2727
- ? this._failedActions.delete(type)
2728
- : this._removeFailure(type, statusKey);
2779
+ let removed = false;
2780
+ for (const t of _toTypeArray(type)) {
2781
+ const removedThis = (statusKey === undefined)
2782
+ ? this._failedActions.delete(t)
2783
+ : this._removeFailure(t, statusKey);
2784
+ removed = removedThis || removed;
2785
+ }
2729
2786
  if (removed)
2730
2787
  this._statusListeners.notify();
2731
2788
  }
@@ -2745,35 +2802,44 @@ class Store {
2745
2802
  this._statusListeners.notify();
2746
2803
  }
2747
2804
  /**
2748
- * Internal: the value `useSuspense` reads as its snapshot, for the given action `type` and
2749
- * `statusKey` (`undefined` matches any key):
2750
- *
2751
- * - A promise, while an action of the type (or of a subclass) with that key is in progress,
2752
- * as `isWaiting` sees it. The same promise object is returned until the action finishes, as
2753
- * React's Suspense needs, and it resolves then (see `_resolveSuspenseWaits`). The promise
2754
- * is created the first time it's asked for, so a store whose components never call
2805
+ * Internal: the value `useSuspense` reads as its snapshot, for the given action `type` (or
2806
+ * array of types) and `statusKey` (`undefined` matches any key):
2807
+ *
2808
+ * - A promise, while an action of the type (or of a subclass), or of any of the types in the
2809
+ * array, with that key is in progress, as `isWaiting` sees it. The same promise object is
2810
+ * returned until no such action is in progress, as React's Suspense needs, and it resolves
2811
+ * then (see `_resolveSuspenseWaits`). Arrays are compared by their content, so an array
2812
+ * written inline in the component gets the same promise on every render. The promise is
2813
+ * created the first time it's asked for, so a store whose components never call
2755
2814
  * `useSuspense` creates none.
2756
2815
  * - Otherwise, when `throwErrors` is true, the failure record of the type with that key, as
2757
- * `isFailed` sees it (the exact type; without a key, the most recent failure). It's the
2758
- * same object until the failure is replaced or cleared.
2816
+ * `isFailed` sees it (the exact type; without a key, the most recent failure). With an
2817
+ * array, the failure of the first type in the array that failed. It's the same object until
2818
+ * the failure is replaced or cleared.
2759
2819
  * - Otherwise `null`.
2760
2820
  *
2761
2821
  * @internal
2762
2822
  */
2763
2823
  _suspenseValue(type, statusKey, throwErrors = true) {
2764
- if (this.isWaiting(type, { statusKey })) {
2765
- let wait = this._suspenseWaits.find(w => w.type === type && (0, KissAction_1._isSameNonReentrantKey)(w.statusKey, statusKey));
2824
+ const types = _toTypeArray(type);
2825
+ if (this.isWaiting(types, { statusKey })) {
2826
+ let wait = this._suspenseWaits.find(w => _isSameTypeArray(w.types, types) && (0, KissAction_1._isSameNonReentrantKey)(w.statusKey, statusKey));
2766
2827
  if (wait === undefined) {
2767
2828
  let resolve;
2768
2829
  const promise = new Promise(r => resolve = r);
2769
- wait = { type, statusKey, promise, resolve };
2830
+ wait = { types: [...types], statusKey, promise, resolve };
2770
2831
  this._suspenseWaits.push(wait);
2771
2832
  }
2772
2833
  return wait.promise;
2773
2834
  }
2774
2835
  if (!throwErrors)
2775
2836
  return null;
2776
- return this._findFailure(type, { statusKey });
2837
+ for (const t of types) {
2838
+ const failure = this._findFailure(t, { statusKey });
2839
+ if (failure !== null)
2840
+ return failure;
2841
+ }
2842
+ return null;
2777
2843
  }
2778
2844
  /**
2779
2845
  * Resolves and removes the `useSuspense` promises whose action is not in progress anymore.
@@ -2784,7 +2850,7 @@ class Store {
2784
2850
  return;
2785
2851
  for (let i = this._suspenseWaits.length - 1; i >= 0; i--) {
2786
2852
  const wait = this._suspenseWaits[i];
2787
- if (!this.isWaiting(wait.type, { statusKey: wait.statusKey })) {
2853
+ if (!this.isWaiting(wait.types, { statusKey: wait.statusKey })) {
2788
2854
  this._suspenseWaits.splice(i, 1);
2789
2855
  wait.resolve();
2790
2856
  }
@@ -3333,7 +3399,7 @@ class Store {
3333
3399
  * don't dispose the store while you still wait for it.
3334
3400
  * 3. Pauses the persistor, and cancels its pending save (a state change waiting for the
3335
3401
  * throttle). A save that is already running still finishes. If you want the current state
3336
- * saved first, call `await store.persistAndPause()` before.
3402
+ * saved first, call `await store.persistAndPausePersistor()` before.
3337
3403
  * 4. Stops listening to the focus and online sources (see `focusSource` and `onlineSource`
3338
3404
  * in the constructor), if they were started. `isFocused` and `isOnline` keep their last
3339
3405
  * values.
@@ -4292,6 +4358,14 @@ class PrintableSet extends Set {
4292
4358
  * days), by chaining timers. A delay of `Infinity` never fires. Returns a function that cancels
4293
4359
  * the timeout.
4294
4360
  */
4361
+ /** Returns the given action type as an array with one type, or the given array of types. */
4362
+ function _toTypeArray(type) {
4363
+ return Array.isArray(type) ? type : [type];
4364
+ }
4365
+ /** True if both arrays have the same action types, in the same order. */
4366
+ function _isSameTypeArray(a, b) {
4367
+ return a.length === b.length && a.every((type, i) => type === b[i]);
4368
+ }
4295
4369
  function _setLongTimeout(callback, millis) {
4296
4370
  if (millis === Infinity)
4297
4371
  return () => { };