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