kiss-for-react 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +555 -0
- package/lib/cjs/ClassPersistor.js +112 -0
- package/lib/cjs/Esserializer/DeserializationOptions.js +4 -0
- package/lib/cjs/Esserializer/SerializeOptions.js +4 -0
- package/lib/cjs/Esserializer/constant.js +131 -0
- package/lib/cjs/Esserializer/deserializer.js +313 -0
- package/lib/cjs/Esserializer/general.js +39 -0
- package/lib/cjs/Esserializer/index.js +43 -0
- package/lib/cjs/Esserializer/serializer.js +133 -0
- package/lib/cjs/Hooks.js +969 -0
- package/lib/cjs/KissAction.js +1268 -0
- package/lib/cjs/Persistor.js +120 -0
- package/lib/cjs/ProcessPersistence.js +262 -0
- package/lib/cjs/Store.js +1534 -0
- package/lib/cjs/StoreException.js +75 -0
- package/lib/cjs/UnmodifiableSetView.js +53 -0
- package/lib/cjs/UserException.js +218 -0
- package/lib/cjs/Wait.js +309 -0
- package/lib/cjs/index.js +42 -0
- package/lib/cjs/types/ClassPersistor.d.ts +113 -0
- package/lib/cjs/types/ClassPersistor.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +7 -0
- package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +6 -0
- package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/constant.d.ts +50 -0
- package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/deserializer.d.ts +18 -0
- package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/general.d.ts +5 -0
- package/lib/cjs/types/Esserializer/general.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/index.d.ts +30 -0
- package/lib/cjs/types/Esserializer/index.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/serializer.d.ts +4 -0
- package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -0
- package/lib/cjs/types/Hooks.d.ts +838 -0
- package/lib/cjs/types/Hooks.d.ts.map +1 -0
- package/lib/cjs/types/KissAction.d.ts +1324 -0
- package/lib/cjs/types/KissAction.d.ts.map +1 -0
- package/lib/cjs/types/Persistor.d.ts +119 -0
- package/lib/cjs/types/Persistor.d.ts.map +1 -0
- package/lib/cjs/types/ProcessPersistence.d.ts +100 -0
- package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -0
- package/lib/cjs/types/Store.d.ts +1043 -0
- package/lib/cjs/types/Store.d.ts.map +1 -0
- package/lib/cjs/types/StoreException.d.ts +29 -0
- package/lib/cjs/types/StoreException.d.ts.map +1 -0
- package/lib/cjs/types/UnmodifiableSetView.d.ts +24 -0
- package/lib/cjs/types/UnmodifiableSetView.d.ts.map +1 -0
- package/lib/cjs/types/UserException.d.ts +170 -0
- package/lib/cjs/types/UserException.d.ts.map +1 -0
- package/lib/cjs/types/Wait.d.ts +1 -0
- package/lib/cjs/types/Wait.d.ts.map +1 -0
- package/lib/cjs/types/index.d.ts +10 -0
- package/lib/cjs/types/index.d.ts.map +1 -0
- package/lib/cjs/types/utils.d.ts +2 -0
- package/lib/cjs/types/utils.d.ts.map +1 -0
- package/lib/cjs/utils.js +7 -0
- package/lib/esm/ClassPersistor.js +112 -0
- package/lib/esm/Esserializer/DeserializationOptions.js +3 -0
- package/lib/esm/Esserializer/SerializeOptions.js +3 -0
- package/lib/esm/Esserializer/constant.js +81 -0
- package/lib/esm/Esserializer/deserializer.js +307 -0
- package/lib/esm/Esserializer/general.js +34 -0
- package/lib/esm/Esserializer/index.js +39 -0
- package/lib/esm/Esserializer/serializer.js +130 -0
- package/lib/esm/Hooks.js +955 -0
- package/lib/esm/KissAction.js +1368 -0
- package/lib/esm/Persistor.js +113 -0
- package/lib/esm/ProcessPersistence.js +262 -0
- package/lib/esm/Store.js +1606 -0
- package/lib/esm/StoreException.js +69 -0
- package/lib/esm/UnmodifiableSetView.js +50 -0
- package/lib/esm/UserException.js +246 -0
- package/lib/esm/Wait.js +309 -0
- package/lib/esm/index.mjs +9 -0
- package/lib/esm/types/ClassPersistor.d.ts +113 -0
- package/lib/esm/types/ClassPersistor.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +7 -0
- package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/SerializeOptions.d.ts +6 -0
- package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/constant.d.ts +50 -0
- package/lib/esm/types/Esserializer/constant.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/deserializer.d.ts +18 -0
- package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/general.d.ts +5 -0
- package/lib/esm/types/Esserializer/general.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/index.d.ts +30 -0
- package/lib/esm/types/Esserializer/index.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/serializer.d.ts +4 -0
- package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -0
- package/lib/esm/types/Hooks.d.ts +838 -0
- package/lib/esm/types/Hooks.d.ts.map +1 -0
- package/lib/esm/types/KissAction.d.ts +1324 -0
- package/lib/esm/types/KissAction.d.ts.map +1 -0
- package/lib/esm/types/Persistor.d.ts +119 -0
- package/lib/esm/types/Persistor.d.ts.map +1 -0
- package/lib/esm/types/ProcessPersistence.d.ts +100 -0
- package/lib/esm/types/ProcessPersistence.d.ts.map +1 -0
- package/lib/esm/types/Store.d.ts +1043 -0
- package/lib/esm/types/Store.d.ts.map +1 -0
- package/lib/esm/types/StoreException.d.ts +29 -0
- package/lib/esm/types/StoreException.d.ts.map +1 -0
- package/lib/esm/types/UnmodifiableSetView.d.ts +24 -0
- package/lib/esm/types/UnmodifiableSetView.d.ts.map +1 -0
- package/lib/esm/types/UserException.d.ts +170 -0
- package/lib/esm/types/UserException.d.ts.map +1 -0
- package/lib/esm/types/Wait.d.ts +1 -0
- package/lib/esm/types/Wait.d.ts.map +1 -0
- package/lib/esm/types/index.d.ts +10 -0
- package/lib/esm/types/index.d.ts.map +1 -0
- package/lib/esm/types/utils.d.ts +2 -0
- package/lib/esm/types/utils.d.ts.map +1 -0
- package/lib/esm/utils.js +3 -0
- package/package.json +87 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Marcelo Glasberg
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
Kiss is:
|
|
4
|
+
|
|
5
|
+
* Simple to learn and easy to use
|
|
6
|
+
* Powerful enough to handle complex apps with millions of users
|
|
7
|
+
* Testable
|
|
8
|
+
|
|
9
|
+
## What is it?
|
|
10
|
+
|
|
11
|
+
An optimized, unofficial version of Redux, written from the ground up,
|
|
12
|
+
created by [Marcelo Glasberg](https://github.com/marcglasberg), launched in July 2024.
|
|
13
|
+
|
|
14
|
+
While new for React, it's a **mature solution** as it's
|
|
15
|
+
been available for Flutter with the name [Async Redux](https://pub.dev/packages/async_redux) for years
|
|
16
|
+
(top 8% of packages), battle-tested in hundreds of real-world applications.
|
|
17
|
+
|
|
18
|
+
## Documentation
|
|
19
|
+
|
|
20
|
+
The Kiss docs are published
|
|
21
|
+
at **[https://kissforreact.org](https://kissforreact.org)**
|
|
22
|
+
|
|
23
|
+
* [Getting Started](https://kissforreact.org/react/intro)
|
|
24
|
+
* [Tutorial: A simple Todo List app](https://kissforreact.org/react/tutorial/setting-up-the-store)
|
|
25
|
+
* [The Basics](https://kissforreact.org/react/basics/store-and-state)
|
|
26
|
+
|
|
27
|
+
## How does it compare?
|
|
28
|
+
|
|
29
|
+
State management solutions can sometimes overwhelm with the complexity of concepts you
|
|
30
|
+
have to grasp and the significant knowledge overhead needed to navigate the pitfalls.
|
|
31
|
+
**Kiss** is the opposite:
|
|
32
|
+
There's no need to be super clever to make things work.
|
|
33
|
+
|
|
34
|
+
[Compare it with Redux Toolkit, TanStack Query, Zustand and Mobx](https://kissforreact.org/react/category/comparisons).
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
# Overview
|
|
39
|
+
|
|
40
|
+
For a quick overview, here are the main concepts:
|
|
41
|
+
|
|
42
|
+
## Store and state
|
|
43
|
+
|
|
44
|
+
The **store** holds all the application **state**. A few examples:
|
|
45
|
+
|
|
46
|
+
```tsx
|
|
47
|
+
// Here, the state is a number
|
|
48
|
+
const store = createStore<number>({initialState: 1});
|
|
49
|
+
|
|
50
|
+
// Here, the state is a plain JS object
|
|
51
|
+
const store = createStore({ initialState: {name: 'Mary', age: 25} });
|
|
52
|
+
|
|
53
|
+
// Here, the state is an ES6 class object
|
|
54
|
+
class State { constructor(public name: string, public age: number){} }
|
|
55
|
+
const store = createStore<State>({ initialState: new State('Mary', 25) });
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
To use the store, add it in a `StoreProvider` at the top of your component tree.
|
|
59
|
+
|
|
60
|
+
```tsx
|
|
61
|
+
function App() {
|
|
62
|
+
return (
|
|
63
|
+
<StoreProvider store={store}>
|
|
64
|
+
<AppContent />
|
|
65
|
+
</StoreProvider>
|
|
66
|
+
);
|
|
67
|
+
};
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
## Components use the state
|
|
73
|
+
|
|
74
|
+
The `useAllState` hook lets you access the state from any component.
|
|
75
|
+
It will rebuild when the state changes.
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
function MyComponent() {
|
|
79
|
+
const state = useAllState();
|
|
80
|
+
|
|
81
|
+
return <div>{state.name} has {state.age} years old</div>;
|
|
82
|
+
};
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The `useSelect` hook selects only the part of the state that your component needs.
|
|
86
|
+
It will rebuild only when that part changes.
|
|
87
|
+
|
|
88
|
+
```tsx
|
|
89
|
+
function MyComponent() {
|
|
90
|
+
const name = useSelect((state) => state.name);
|
|
91
|
+
const age = useSelect((state) => state.age);
|
|
92
|
+
|
|
93
|
+
return <div>{name} has {age} years old</div>;
|
|
94
|
+
};
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The `useObject` hook is another alternative that only rebuilds when needed:
|
|
98
|
+
|
|
99
|
+
```tsx
|
|
100
|
+
function MyComponent() {
|
|
101
|
+
|
|
102
|
+
const state = useObject((state) => {
|
|
103
|
+
name: state.name,
|
|
104
|
+
age: state.age
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
return <div>{state.name} has {state.age} years old</div>;
|
|
108
|
+
};
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
## Actions and reducers
|
|
114
|
+
|
|
115
|
+
An **action** is a class that contain its own **reducer**.
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
class Increment extends Action {
|
|
119
|
+
|
|
120
|
+
reduce() {
|
|
121
|
+
// The reducer has access to the current state
|
|
122
|
+
return this.state + 1; // It returns a new state
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
## Dispatch an action
|
|
130
|
+
|
|
131
|
+
The store state is **immutable**.
|
|
132
|
+
|
|
133
|
+
The only way to change the store **state** is by dispatching an **action**.
|
|
134
|
+
The action reducer returns a new state, that replaces the old one.
|
|
135
|
+
|
|
136
|
+
```tsx
|
|
137
|
+
// Dispatch an action
|
|
138
|
+
store.dispatch(new Increment());
|
|
139
|
+
|
|
140
|
+
// Dispatch multiple actions
|
|
141
|
+
store.dispatchAll([new Increment(), new LoadText()]);
|
|
142
|
+
|
|
143
|
+
// Dispatch an action and wait for it to finish
|
|
144
|
+
await store.dispatchAndWait(new Increment());
|
|
145
|
+
|
|
146
|
+
// Dispatch multiple actions and wait for them to finish
|
|
147
|
+
await store.dispatchAndWaitAll([new Increment(), new LoadText()]);
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
## Components can dispatch actions
|
|
153
|
+
|
|
154
|
+
The hooks to dispatch actions are `useDispatch` , `useDispatchAll` etc.
|
|
155
|
+
|
|
156
|
+
```tsx
|
|
157
|
+
function MyComponent() {
|
|
158
|
+
const dispatch = useDispatch();
|
|
159
|
+
|
|
160
|
+
return (
|
|
161
|
+
<Button onClick={() => dispatch(new LoadText())}>
|
|
162
|
+
Click me!
|
|
163
|
+
</Button>
|
|
164
|
+
);
|
|
165
|
+
};
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Or getting the store with `useStore` also allows you to dispatch actions:
|
|
169
|
+
|
|
170
|
+
```tsx
|
|
171
|
+
function MyComponent() {
|
|
172
|
+
const store = useStore();
|
|
173
|
+
|
|
174
|
+
return (
|
|
175
|
+
<Button onClick={() => store.dispatch(new LoadText())}>
|
|
176
|
+
Click me!
|
|
177
|
+
</Button>
|
|
178
|
+
);
|
|
179
|
+
};
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
## Actions can do asynchronous work
|
|
185
|
+
|
|
186
|
+
They can download information from the internet, or do any other async work.
|
|
187
|
+
|
|
188
|
+
```tsx
|
|
189
|
+
const store = createStore<string>({initialState: ''});
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
```tsx
|
|
193
|
+
class LoadText extends Action {
|
|
194
|
+
|
|
195
|
+
// This reducer returns a Promise
|
|
196
|
+
async reduce() {
|
|
197
|
+
|
|
198
|
+
// Download something from the internet
|
|
199
|
+
let response = await fetch('https://dummyjson.com/todos/1');
|
|
200
|
+
let text = await response.text();
|
|
201
|
+
|
|
202
|
+
// Change the state with the downloaded information
|
|
203
|
+
return (state) => text;
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
## Actions can throw errors
|
|
210
|
+
|
|
211
|
+
If something bad happens, you can simply **throw an error**. In this case, the state will not
|
|
212
|
+
change. Errors are caught globally and can be handled in a central place, later.
|
|
213
|
+
|
|
214
|
+
In special, if you throw a `UserException`, which is a type provided by Kiss,
|
|
215
|
+
a dialog (or other UI) will open automatically, showing the error message to the user.
|
|
216
|
+
|
|
217
|
+
```tsx
|
|
218
|
+
class LoadText extends Action {
|
|
219
|
+
|
|
220
|
+
async reduce() {
|
|
221
|
+
let response = await fetch("https://dummyjson.com/todos/random/1");
|
|
222
|
+
if (!response.ok) throw new UserException("Failed to load.");
|
|
223
|
+
|
|
224
|
+
let text = await response.text();
|
|
225
|
+
return (state) => text;
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
## Components can react to actions
|
|
232
|
+
|
|
233
|
+
To show a spinner while an asynchronous action is running, use `isWaiting(action)`.
|
|
234
|
+
|
|
235
|
+
To show an error message inside the component, use `isFailed(action)`.
|
|
236
|
+
|
|
237
|
+
```tsx
|
|
238
|
+
function MyComponent() {
|
|
239
|
+
|
|
240
|
+
const isWaiting = useIsWaiting(LoadText);
|
|
241
|
+
const isFailed = useIsFailed(LoadText);
|
|
242
|
+
const state = useAllState();
|
|
243
|
+
|
|
244
|
+
if (isWaiting) return <CircularProgress />
|
|
245
|
+
if (isFailed) return <p>Loading failed...</p>;
|
|
246
|
+
return <p>{state}</p>;
|
|
247
|
+
}
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
## Actions can dispatch other actions
|
|
253
|
+
|
|
254
|
+
You can use `dispatchAndWait` to dispatch an action and wait for it to finish.
|
|
255
|
+
|
|
256
|
+
```tsx
|
|
257
|
+
class LoadTextAndIncrement extends Action {
|
|
258
|
+
|
|
259
|
+
async reduce() {
|
|
260
|
+
|
|
261
|
+
// Dispatch and wait for the action to finish
|
|
262
|
+
await this.dispatchAndWait(new LoadText());
|
|
263
|
+
|
|
264
|
+
// Only then, increment the state
|
|
265
|
+
return (state) => state.copy({ count: state.count + 1 });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
You can also dispatch actions in **parallel** and wait for them to finish:
|
|
271
|
+
|
|
272
|
+
```tsx
|
|
273
|
+
class BuyAndSell extends Action {
|
|
274
|
+
|
|
275
|
+
async reduce() {
|
|
276
|
+
|
|
277
|
+
// Dispatch and wait for both actions to finish
|
|
278
|
+
await this.dispatchAndWaitAll([
|
|
279
|
+
new BuyAction('IBM'),
|
|
280
|
+
new SellAction('TSLA')
|
|
281
|
+
]);
|
|
282
|
+
|
|
283
|
+
return (state) => state.copy({
|
|
284
|
+
message: `New cash balance is ${this.state.cash}`
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
You can also use `waitCondition` to wait until the `state` changes in a certain way:
|
|
291
|
+
|
|
292
|
+
```tsx
|
|
293
|
+
class SellStockForPrice extends Action {
|
|
294
|
+
constructor(public stock: string, public price: number) { super(); }
|
|
295
|
+
|
|
296
|
+
async reduce() {
|
|
297
|
+
|
|
298
|
+
// Wait until the stock price is higher than the limit price
|
|
299
|
+
await this.waitCondition(
|
|
300
|
+
(state) => state.stocks.getPrice(this.stock) >= this.price
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
// Only then, post the sell order to the backend
|
|
304
|
+
let amount = await postSellOrder(this.stock);
|
|
305
|
+
|
|
306
|
+
return (state) =>
|
|
307
|
+
state.copy(
|
|
308
|
+
stocks: state.stocks.setAmount(this.stock, amount),
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
## Add features to your actions
|
|
317
|
+
|
|
318
|
+
It's easy to add your own reusable "features" to your actions,
|
|
319
|
+
but they come out of the box with some interesting ones:
|
|
320
|
+
|
|
321
|
+
## NonReentrant
|
|
322
|
+
|
|
323
|
+
To prevent an action from being dispatched while it's already running,
|
|
324
|
+
add the `nonReentrant` property to your action class and set it to `true`.
|
|
325
|
+
|
|
326
|
+
```tsx
|
|
327
|
+
class LoadText extends Action {
|
|
328
|
+
nonReentrant = true;
|
|
329
|
+
|
|
330
|
+
reduce() { ... }
|
|
331
|
+
}
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
## Retry
|
|
335
|
+
|
|
336
|
+
If an action fails, to retry it a few times with exponential backoff,
|
|
337
|
+
add the `retry` property to your action class.
|
|
338
|
+
|
|
339
|
+
```tsx
|
|
340
|
+
class LoadText extends Action {
|
|
341
|
+
retry = {on: true}
|
|
342
|
+
|
|
343
|
+
reduce() { ... }
|
|
344
|
+
}
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
And you can specify the retry policy:
|
|
348
|
+
|
|
349
|
+
```tsx
|
|
350
|
+
class LoadText extends Action {
|
|
351
|
+
|
|
352
|
+
retry = {
|
|
353
|
+
initialDelay: 350, // Millisecond delay before the first attempt
|
|
354
|
+
maxRetries: 3, // Number of retries before giving up
|
|
355
|
+
multiplier: 2, // Delay increase factor for each retry
|
|
356
|
+
maxDelay: 5000, // Max millisecond delay between retries
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
reduce() { ... }
|
|
360
|
+
}
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
## Debounce
|
|
364
|
+
|
|
365
|
+
To limit how often an action occurs in response to rapid inputs, you can add a `debounce` property
|
|
366
|
+
to your action class. For example, when a user types in a search bar, debouncing ensures that not
|
|
367
|
+
every keystroke triggers a server request. Instead, it waits until the user pauses typing before
|
|
368
|
+
acting.
|
|
369
|
+
|
|
370
|
+
```tsx
|
|
371
|
+
class SearchText extends Action {
|
|
372
|
+
constructor(public searchTerm: string) { super(); }
|
|
373
|
+
|
|
374
|
+
debounce = 300 // Milliseconds
|
|
375
|
+
|
|
376
|
+
async reduce() {
|
|
377
|
+
let result = await loadJson('https://example.com/?q=', searchTerm);
|
|
378
|
+
return (state) => state.copy({searchResult: result});
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
## Throttle
|
|
384
|
+
|
|
385
|
+
To prevent an action from running too frequently, you can add a `throttle` property to your
|
|
386
|
+
action class. This means that once the action runs it's considered _fresh_, and it won't run
|
|
387
|
+
again for a set period of time, even if you try to dispatch it.
|
|
388
|
+
After this period ends, the action is considered _stale_ and is ready to run again.
|
|
389
|
+
|
|
390
|
+
```tsx
|
|
391
|
+
class LoadPrices extends Action {
|
|
392
|
+
|
|
393
|
+
throttle = 5000 // Milliseconds
|
|
394
|
+
|
|
395
|
+
async reduce() {
|
|
396
|
+
let result = await loadJson('https://example.com/prices');
|
|
397
|
+
return (state) => state.copy({prices: result});
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
## CheckInternet
|
|
403
|
+
|
|
404
|
+
Automatically checks if there is an internet connection before running the action.
|
|
405
|
+
If there is no internet, the action aborts. Optionally, it can show a dialog to the user
|
|
406
|
+
saying something like: "There is no Internet, please verify your connection".
|
|
407
|
+
|
|
408
|
+
```tsx
|
|
409
|
+
class LoadPrices extends Action {
|
|
410
|
+
|
|
411
|
+
checkInternet = { dialog: true }
|
|
412
|
+
|
|
413
|
+
async reduce() { ... }
|
|
414
|
+
}
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
## OptimisticUpdate
|
|
418
|
+
|
|
419
|
+
To provide instant feedback on actions that save information to the server, this feature immediately
|
|
420
|
+
applies state changes as if they were already successful, before confirming with the server.
|
|
421
|
+
If the server update fails, the change is rolled back and, optionally, a notification can inform
|
|
422
|
+
the user of the issue.
|
|
423
|
+
|
|
424
|
+
```tsx
|
|
425
|
+
class SaveName extends Action {
|
|
426
|
+
|
|
427
|
+
optimisticUpdate = { ... }
|
|
428
|
+
|
|
429
|
+
async reduce() { ... }
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
## Persist the state
|
|
436
|
+
|
|
437
|
+
You can add a `persistor` to save the state to the local device disk.
|
|
438
|
+
It supports serializing JavaScript objects **and** ES6 classes out of the box.
|
|
439
|
+
|
|
440
|
+
```tsx
|
|
441
|
+
const store = createStore<State>({
|
|
442
|
+
persistor: new Persistor(),
|
|
443
|
+
});
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
## Testing your app is easy
|
|
449
|
+
|
|
450
|
+
Just dispatch actions and wait for them to finish.
|
|
451
|
+
Then, verify the new state or check if some error was thrown.
|
|
452
|
+
|
|
453
|
+
```tsx
|
|
454
|
+
class State {
|
|
455
|
+
constructor(
|
|
456
|
+
public items: string[],
|
|
457
|
+
public selectedItem: number
|
|
458
|
+
) {}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
test('Selecting an item', async () => {
|
|
462
|
+
|
|
463
|
+
const store = createStore<State>({
|
|
464
|
+
initialState: new State(['A', 'B', 'C'], -1);
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
// Should select item 2
|
|
468
|
+
await store.dispatchAndWait(new SelectItem(2));
|
|
469
|
+
expect(store.state.selectedItem).toBe('B');
|
|
470
|
+
|
|
471
|
+
// Fail to select item 42
|
|
472
|
+
let status = await store.dispatchAndWait(new SelectItem(42));
|
|
473
|
+
expect(status.originalError).toBeInstanceOf(UserException);
|
|
474
|
+
});
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
## Advanced setup
|
|
480
|
+
|
|
481
|
+
If you are the Team Lead, you set up the app's infrastructure in a central place,
|
|
482
|
+
and allow your developers to concentrate solely on the business logic.
|
|
483
|
+
|
|
484
|
+
You can add a `stateObserver` to collect app metrics, an `errorObserver` to log errors,
|
|
485
|
+
an `actionObserver` to print information to the console during development,
|
|
486
|
+
and a `globalWrapError` to catch all errors.
|
|
487
|
+
|
|
488
|
+
```tsx
|
|
489
|
+
const store = createStore<string>({
|
|
490
|
+
stateObserver: (action, prevState, newState, error, count) => { ... },
|
|
491
|
+
errorObserver: (error, action, store) => { ... }
|
|
492
|
+
actionObserver: (action, count, ini) => { ... }
|
|
493
|
+
globalWrapError: (error) => { ... }
|
|
494
|
+
});
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
For example, here we handle `FirestoreError` errors thrown by Firebase.
|
|
498
|
+
We convert them into `UserException` errors, which are built-in types that
|
|
499
|
+
automatically show a message to the user in an error dialog:
|
|
500
|
+
|
|
501
|
+
```tsx
|
|
502
|
+
globalWrapError: (error: any) => {
|
|
503
|
+
return (error instanceof FirestoreError)
|
|
504
|
+
? UserException('Error connecting to Firebase')
|
|
505
|
+
: error;
|
|
506
|
+
}
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
## Advanced action configuration
|
|
512
|
+
|
|
513
|
+
The Team Lead may create a base action class that all actions will extend, and add some common
|
|
514
|
+
functionality to it. For example, add getter shortcuts to important parts of the state,
|
|
515
|
+
and selectors to help find information.
|
|
516
|
+
|
|
517
|
+
```tsx
|
|
518
|
+
class State {
|
|
519
|
+
items: Item[];
|
|
520
|
+
selectedItem: number;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
export abstract class Action extends KissAction<State> {
|
|
524
|
+
|
|
525
|
+
// Getter shortcuts
|
|
526
|
+
get items() { return this.state.items; }
|
|
527
|
+
get selectedItem() { return this.state.selectedItem; }
|
|
528
|
+
|
|
529
|
+
// Selectors
|
|
530
|
+
findById(id) { return this.items.find((item) => item.id === id); }
|
|
531
|
+
get selectedIndex() { return this.items.indexOf(this.selectedItem); }
|
|
532
|
+
searchByText(text) { return this.items.find((item) => item.text.includes(text)); }
|
|
533
|
+
}
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
Now, all actions can use them to access the state in their reducers:
|
|
537
|
+
|
|
538
|
+
```tsx
|
|
539
|
+
class SelectItem extends Action {
|
|
540
|
+
constructor(public id: number) { super(); }
|
|
541
|
+
|
|
542
|
+
reduce() {
|
|
543
|
+
let item = this.findById(this.id);
|
|
544
|
+
if (item === undefined) throw new Error('Item not found');
|
|
545
|
+
return this.state.copy({selectedItem: item});
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
```
|
|
549
|
+
|
|
550
|
+
---
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
_To learn more, the complete Kiss documentation is published
|
|
555
|
+
at **[https://kissforreact.org](https://kissforreact.org)**_
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ClassPersistor = void 0;
|
|
4
|
+
const Esserializer_1 = require("./Esserializer");
|
|
5
|
+
const Persistor_1 = require("./Persistor");
|
|
6
|
+
/**
|
|
7
|
+
* Use it like this:
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* const store = createStore<AppState>({
|
|
11
|
+
* initialState: initialState,
|
|
12
|
+
* persistor: new MyPersistor(),
|
|
13
|
+
* });
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Example for web:
|
|
17
|
+
* ```
|
|
18
|
+
* return new ClassPersistor<State>(
|
|
19
|
+
* async () => window.localStorage.getItem('state'),
|
|
20
|
+
* async (serialized) => window.localStorage.setItem('state', serialized),
|
|
21
|
+
* async () => window.localStorage.clear(),
|
|
22
|
+
* [State, TodoList, TodoItem, Filter] // All state classes the app uses.
|
|
23
|
+
* );
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Example for React Native:
|
|
27
|
+
* ```
|
|
28
|
+
* return new ClassPersistor<State>(
|
|
29
|
+
* async () => AsyncStorage.getItem('state'),
|
|
30
|
+
* async (serialized) => AsyncStorage.setItem('state', serialized),
|
|
31
|
+
* async () => AsyncStorage.clear(),
|
|
32
|
+
* [State, TodoList, TodoItem, Filter] // All state classes the app uses.
|
|
33
|
+
* );
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
class ClassPersistor extends Persistor_1.Persistor {
|
|
37
|
+
constructor(
|
|
38
|
+
/**
|
|
39
|
+
* Returns the serialized state. You can use this to load from localStorage or IndexedDB
|
|
40
|
+
* (in React web), or AsyncStorage (in React Native) or other.
|
|
41
|
+
* It should return a Promise that resolves to the serialized state, or to null if the state
|
|
42
|
+
* is not yet persisted.
|
|
43
|
+
*/
|
|
44
|
+
loadSerialized,
|
|
45
|
+
//
|
|
46
|
+
/**
|
|
47
|
+
* Saves the given serialized state. You can use this to save to localStorage or IndexedDB
|
|
48
|
+
* (in React web), or AsyncStorage (in React Native) or other.
|
|
49
|
+
* It should return a Promise that resolves when the state is saved.
|
|
50
|
+
*/
|
|
51
|
+
saveSerialized,
|
|
52
|
+
//
|
|
53
|
+
/**
|
|
54
|
+
* Deletes the serialized state. You can use this to delete from the localStorage or IndexedDB
|
|
55
|
+
* (in React web), or AsyncStorage (in React Native) or other.
|
|
56
|
+
* It should return a Promise that resolves when the state is deleted.
|
|
57
|
+
*/
|
|
58
|
+
deleteSerialized,
|
|
59
|
+
//
|
|
60
|
+
/**
|
|
61
|
+
* You HAVE to list here all the custom classes that are part of your state, directly or
|
|
62
|
+
* indirectly. Note: You don't need to list native JavaScript classes, like Date.
|
|
63
|
+
* For example, suppose you have a class `State` that has a property `todoList` of
|
|
64
|
+
* type `TodoList`.
|
|
65
|
+
* And the class `TodoList` has a property `items` of type `Array<TodoItem>`.
|
|
66
|
+
* Then you have to list all three classes here: `[State, TodoList, TodoItem]`.
|
|
67
|
+
*/
|
|
68
|
+
classesToSerialize) {
|
|
69
|
+
super();
|
|
70
|
+
this.loadSerialized = loadSerialized;
|
|
71
|
+
this.saveSerialized = saveSerialized;
|
|
72
|
+
this.deleteSerialized = deleteSerialized;
|
|
73
|
+
this.classesToSerialize = classesToSerialize;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Read the saved state from the persistence. Should return null if the state is not yet
|
|
77
|
+
* persisted. This method should be called only once, when the app starts, before the store
|
|
78
|
+
* is created. The state it returns may become the store's initial-state. If some error
|
|
79
|
+
* occurs while loading the info, we have to deal with it by fixing the problem. In the worse
|
|
80
|
+
* case, if we think the state is corrupted and cannot be fixed, one alternative is deleting
|
|
81
|
+
* all persisted files and returning null.
|
|
82
|
+
*/
|
|
83
|
+
async readState() {
|
|
84
|
+
// Reads the JSON file as a string.
|
|
85
|
+
const serializedString = await this.loadSerialized();
|
|
86
|
+
if (serializedString === null)
|
|
87
|
+
return null;
|
|
88
|
+
Esserializer_1.ESSerializer.registerClasses(this.classesToSerialize);
|
|
89
|
+
return Esserializer_1.ESSerializer.deserialize(serializedString);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Save an initial-state to the persistence.
|
|
93
|
+
*/
|
|
94
|
+
async saveInitialState(state) {
|
|
95
|
+
const serializedString = Esserializer_1.ESSerializer.serialize(state);
|
|
96
|
+
await this.saveSerialized(serializedString);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Delete the saved state from the persistence.
|
|
100
|
+
*/
|
|
101
|
+
async deleteState() {
|
|
102
|
+
return this.deleteSerialized();
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* We assume the state is small, and we save `newState` everytime, ignoring `lastPersistedState`.
|
|
106
|
+
*/
|
|
107
|
+
async persistDifference(_lastPersistedState, newState) {
|
|
108
|
+
const serializedString = Esserializer_1.ESSerializer.serialize(newState);
|
|
109
|
+
await this.saveSerialized(serializedString);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
exports.ClassPersistor = ClassPersistor;
|