kiss-for-react 1.0.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +699 -156
  2. package/lib/cjs/ClassPersistor.js +177 -112
  3. package/lib/cjs/Esserializer/DeserializationOptions.js +4 -4
  4. package/lib/cjs/Esserializer/SerializeOptions.js +4 -4
  5. package/lib/cjs/Esserializer/builtins.js +258 -0
  6. package/lib/cjs/Esserializer/constant.js +39 -131
  7. package/lib/cjs/Esserializer/deserializer.js +226 -313
  8. package/lib/cjs/Esserializer/general.js +91 -39
  9. package/lib/cjs/Esserializer/index.js +47 -43
  10. package/lib/cjs/Esserializer/serializer.js +168 -133
  11. package/lib/cjs/Evt.js +132 -0
  12. package/lib/cjs/Hooks.js +1472 -969
  13. package/lib/cjs/KissAction.js +4635 -1333
  14. package/lib/cjs/LoadPages.js +336 -0
  15. package/lib/cjs/Persistor.js +189 -120
  16. package/lib/cjs/ProcessPersistence.js +579 -262
  17. package/lib/cjs/Store.js +4278 -1534
  18. package/lib/cjs/StoreException.js +162 -75
  19. package/lib/cjs/StoreProvider.js +88 -0
  20. package/lib/cjs/UserException.js +212 -218
  21. package/lib/cjs/Wait.js +309 -309
  22. package/lib/cjs/index.js +69 -42
  23. package/lib/cjs/server.js +54 -0
  24. package/lib/cjs/types/ClassPersistor.d.ts +143 -112
  25. package/lib/cjs/types/ClassPersistor.d.ts.map +1 -1
  26. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +13 -6
  27. package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  28. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +11 -5
  29. package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  30. package/lib/cjs/types/Esserializer/builtins.d.ts +36 -0
  31. package/lib/cjs/types/Esserializer/builtins.d.ts.map +1 -0
  32. package/lib/cjs/types/Esserializer/constant.d.ts +25 -49
  33. package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -1
  34. package/lib/cjs/types/Esserializer/deserializer.d.ts +27 -17
  35. package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
  36. package/lib/cjs/types/Esserializer/general.d.ts +28 -4
  37. package/lib/cjs/types/Esserializer/general.d.ts.map +1 -1
  38. package/lib/cjs/types/Esserializer/index.d.ts +33 -29
  39. package/lib/cjs/types/Esserializer/index.d.ts.map +1 -1
  40. package/lib/cjs/types/Esserializer/serializer.d.ts +14 -3
  41. package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -1
  42. package/lib/cjs/types/Evt.d.ts +124 -0
  43. package/lib/cjs/types/Evt.d.ts.map +1 -0
  44. package/lib/cjs/types/Hooks.d.ts +1174 -837
  45. package/lib/cjs/types/Hooks.d.ts.map +1 -1
  46. package/lib/cjs/types/KissAction.d.ts +5199 -1398
  47. package/lib/cjs/types/KissAction.d.ts.map +1 -1
  48. package/lib/cjs/types/LoadPages.d.ts +287 -0
  49. package/lib/cjs/types/LoadPages.d.ts.map +1 -0
  50. package/lib/cjs/types/Persistor.d.ts +187 -118
  51. package/lib/cjs/types/Persistor.d.ts.map +1 -1
  52. package/lib/cjs/types/ProcessPersistence.d.ts +197 -99
  53. package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -1
  54. package/lib/cjs/types/Store.d.ts +2253 -1042
  55. package/lib/cjs/types/Store.d.ts.map +1 -1
  56. package/lib/cjs/types/StoreException.d.ts +97 -28
  57. package/lib/cjs/types/StoreException.d.ts.map +1 -1
  58. package/lib/cjs/types/StoreProvider.d.ts +80 -0
  59. package/lib/cjs/types/StoreProvider.d.ts.map +1 -0
  60. package/lib/cjs/types/UserException.d.ts +178 -169
  61. package/lib/cjs/types/UserException.d.ts.map +1 -1
  62. package/lib/cjs/types/index.d.ts +12 -9
  63. package/lib/cjs/types/index.d.ts.map +1 -1
  64. package/lib/cjs/types/server.d.ts +12 -0
  65. package/lib/cjs/types/server.d.ts.map +1 -0
  66. package/lib/cjs/types/utils.d.ts +15 -1
  67. package/lib/cjs/types/utils.d.ts.map +1 -1
  68. package/lib/cjs/utils.js +45 -7
  69. package/lib/esm/ClassPersistor.mjs +177 -0
  70. package/lib/esm/Esserializer/{DeserializationOptions.js → DeserializationOptions.mjs} +3 -3
  71. package/lib/esm/Esserializer/{SerializeOptions.js → SerializeOptions.mjs} +3 -3
  72. package/lib/esm/Esserializer/builtins.mjs +254 -0
  73. package/lib/esm/Esserializer/constant.mjs +28 -0
  74. package/lib/esm/Esserializer/deserializer.mjs +221 -0
  75. package/lib/esm/Esserializer/general.mjs +81 -0
  76. package/lib/esm/Esserializer/index.mjs +43 -0
  77. package/lib/esm/Esserializer/serializer.mjs +164 -0
  78. package/lib/esm/Evt.mjs +151 -0
  79. package/lib/esm/Hooks.mjs +1446 -0
  80. package/lib/esm/KissAction.mjs +4689 -0
  81. package/lib/esm/LoadPages.mjs +340 -0
  82. package/lib/esm/Persistor.mjs +180 -0
  83. package/lib/esm/ProcessPersistence.mjs +581 -0
  84. package/lib/esm/Store.mjs +4400 -0
  85. package/lib/esm/StoreException.mjs +153 -0
  86. package/lib/esm/StoreProvider.mjs +80 -0
  87. package/lib/esm/{UserException.js → UserException.mjs} +240 -246
  88. package/lib/esm/{Wait.js → Wait.mjs} +309 -309
  89. package/lib/esm/index.mjs +12 -9
  90. package/lib/esm/server.mjs +23 -0
  91. package/lib/esm/types/ClassPersistor.d.ts +143 -112
  92. package/lib/esm/types/ClassPersistor.d.ts.map +1 -1
  93. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +13 -6
  94. package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
  95. package/lib/esm/types/Esserializer/SerializeOptions.d.ts +11 -5
  96. package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -1
  97. package/lib/esm/types/Esserializer/builtins.d.ts +36 -0
  98. package/lib/esm/types/Esserializer/builtins.d.ts.map +1 -0
  99. package/lib/esm/types/Esserializer/constant.d.ts +25 -49
  100. package/lib/esm/types/Esserializer/constant.d.ts.map +1 -1
  101. package/lib/esm/types/Esserializer/deserializer.d.ts +27 -17
  102. package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
  103. package/lib/esm/types/Esserializer/general.d.ts +28 -4
  104. package/lib/esm/types/Esserializer/general.d.ts.map +1 -1
  105. package/lib/esm/types/Esserializer/index.d.ts +33 -29
  106. package/lib/esm/types/Esserializer/index.d.ts.map +1 -1
  107. package/lib/esm/types/Esserializer/serializer.d.ts +14 -3
  108. package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -1
  109. package/lib/esm/types/Evt.d.ts +124 -0
  110. package/lib/esm/types/Evt.d.ts.map +1 -0
  111. package/lib/esm/types/Hooks.d.ts +1174 -837
  112. package/lib/esm/types/Hooks.d.ts.map +1 -1
  113. package/lib/esm/types/KissAction.d.ts +5199 -1398
  114. package/lib/esm/types/KissAction.d.ts.map +1 -1
  115. package/lib/esm/types/LoadPages.d.ts +287 -0
  116. package/lib/esm/types/LoadPages.d.ts.map +1 -0
  117. package/lib/esm/types/Persistor.d.ts +187 -118
  118. package/lib/esm/types/Persistor.d.ts.map +1 -1
  119. package/lib/esm/types/ProcessPersistence.d.ts +197 -99
  120. package/lib/esm/types/ProcessPersistence.d.ts.map +1 -1
  121. package/lib/esm/types/Store.d.ts +2253 -1042
  122. package/lib/esm/types/Store.d.ts.map +1 -1
  123. package/lib/esm/types/StoreException.d.ts +97 -28
  124. package/lib/esm/types/StoreException.d.ts.map +1 -1
  125. package/lib/esm/types/StoreProvider.d.ts +80 -0
  126. package/lib/esm/types/StoreProvider.d.ts.map +1 -0
  127. package/lib/esm/types/UserException.d.ts +178 -169
  128. package/lib/esm/types/UserException.d.ts.map +1 -1
  129. package/lib/esm/types/index.d.ts +12 -9
  130. package/lib/esm/types/index.d.ts.map +1 -1
  131. package/lib/esm/types/server.d.ts +12 -0
  132. package/lib/esm/types/server.d.ts.map +1 -0
  133. package/lib/esm/types/utils.d.ts +15 -1
  134. package/lib/esm/types/utils.d.ts.map +1 -1
  135. package/lib/esm/utils.mjs +38 -0
  136. package/package.json +55 -31
  137. package/lib/cjs/UnmodifiableSetView.js +0 -53
  138. package/lib/cjs/types/UnmodifiableSetView.d.ts +0 -24
  139. package/lib/cjs/types/UnmodifiableSetView.d.ts.map +0 -1
  140. package/lib/esm/ClassPersistor.js +0 -112
  141. package/lib/esm/Esserializer/constant.js +0 -81
  142. package/lib/esm/Esserializer/deserializer.js +0 -307
  143. package/lib/esm/Esserializer/general.js +0 -34
  144. package/lib/esm/Esserializer/index.js +0 -39
  145. package/lib/esm/Esserializer/serializer.js +0 -130
  146. package/lib/esm/Hooks.js +0 -955
  147. package/lib/esm/KissAction.js +0 -1459
  148. package/lib/esm/Persistor.js +0 -113
  149. package/lib/esm/ProcessPersistence.js +0 -262
  150. package/lib/esm/Store.js +0 -1606
  151. package/lib/esm/StoreException.js +0 -69
  152. package/lib/esm/UnmodifiableSetView.js +0 -50
  153. package/lib/esm/types/UnmodifiableSetView.d.ts +0 -24
  154. package/lib/esm/types/UnmodifiableSetView.d.ts.map +0 -1
  155. package/lib/esm/utils.js +0 -3
package/README.md CHANGED
@@ -1,29 +1,37 @@
1
1
  <img src="https://kissforreact.org/img/KISS_outline.svg" alt="Kiss for React Image" width="150" />
2
2
 
3
- * Simple to learn and easy to use
4
- * Powerful enough to handle complex apps with millions of users
5
- * Testable
6
- <br></br>
3
+ **State management for React, built for AI agents:**
7
4
 
8
- ## What is it?
5
+ - Helps the AI write well-structured code, separating business logic and UI
6
+ - Forces the AI to write predictable, testable, maintainable code
7
+ - Promotes less token usage, saving money!
8
+ - Comes with a linter that enforces good practices without spending tokens
9
+ - For the human: Final code is easy to read and understand
9
10
 
10
- Kiss is a state management package for React, launched in May 2025. While new to React, it's a **mature solution**, having been available for Flutter for years under the name [Async Redux](https://pub.dev/packages/async_redux) (top 8% of packages), battle-tested in hundreds of real-world applications.
11
+ ```bash
12
+ npm install kiss-for-react
13
+ ```
14
+
15
+ ## Complete docs → **[https://kissforreact.org](https://kissforreact.org)**
11
16
 
12
- ## Documentation
17
+ * [Getting Started](https://kissforreact.org/react/intro) / [Tutorial: A simple Todo List app](https://kissforreact.org/react/tutorial/setting-up-the-store) / [The Basics](https://kissforreact.org/react/basics/store-and-state)
18
+ * [Complete AI Docs](https://kissforreact.org/kiss-state-management-docs.md): Single file
19
+ with all Kiss docs, optimized for AI agents.
20
+ Just copy the link and paste it into any AI.
13
21
 
14
- The Kiss docs are published
15
- at **[https://kissforreact.org](https://kissforreact.org)**
22
+ ### Linter and Quick fixes → [eslint-plugin-kiss-for-react](https://www.npmjs.com/package/eslint-plugin-kiss-for-react)
16
23
 
17
- * [Getting Started](https://kissforreact.org/react/intro)
18
- * [Tutorial: A simple Todo List app](https://kissforreact.org/react/tutorial/setting-up-the-store)
19
- * [The Basics](https://kissforreact.org/react/basics/store-and-state)
24
+ ## Why it helps AI agents
20
25
 
21
- ## How does it compare?
26
+ Kiss improves AI-driven code generation by giving the AI strong guardrails
27
+ that force it to do the right thing while saving tokens.
28
+ [Read about it here](https://kissforreact.org/react/category/ai).
22
29
 
23
- State management solutions can sometimes overwhelm you with complex concepts and the significant knowledge overhead needed to avoid pitfalls. Kiss is the opposite, as there's no need to be especially clever to make things work.
24
- [Detailed comparison](https://kissforreact.org/react/category/comparisons).
30
+ ## For the human
25
31
 
26
- **AI ready:** Kiss centralizes state and business logic in predictable ways, making it easier for AI models to reason about code. This improves AI-driven generation, and helps you achieve results with surprisingly little effort.
32
+ AI can sometimes create code that works but seems alien when you read it.
33
+ With Kiss the code remains human-readable the whole time.
34
+ [Read about it here](https://kissforreact.org/react/category/ai).
27
35
 
28
36
  ---
29
37
 
@@ -33,21 +41,21 @@ Here are the main concepts:
33
41
 
34
42
  ## Store and state
35
43
 
36
- The **store** holds all the application **state**. A few examples:
44
+ The **store** holds all application **state**. Here are a few examples:
37
45
 
38
46
  ```tsx
39
- // Here, the state is a number
47
+ // Your state is a number
40
48
  const store = createStore<number>({initialState: 1});
41
49
 
42
- // Here, the state is a plain JS object
43
- const store = createStore({ initialState: {name: 'Mary', age: 25} });
50
+ // Your state is a plain JavaScript object
51
+ const store = createStore({initialState: {name: 'Mary', age: 25}});
44
52
 
45
- // Here, the state is an ES6 class object
53
+ // Your state is an instance of an ES6 class
46
54
  class State { constructor(public name: string, public age: number){} }
47
- const store = createStore<State>({ initialState: new State('Mary', 25) });
55
+ const store = createStore<State>({initialState: new State('Mary', 25)});
48
56
  ```
49
57
 
50
- To use the store, add it in a `StoreProvider` at the top of your component tree.
58
+ Use a `StoreProvider` to add the store to your component tree:
51
59
 
52
60
  ```tsx
53
61
  function App() {
@@ -63,48 +71,58 @@ function App() {
63
71
 
64
72
  ## Components use the state
65
73
 
66
- The `useAllState` hook lets you access the state from any component.
67
- It will rebuild when the state changes.
74
+ The `useAllState` hook lets you access the whole state from any component.
75
+ The component re-renders when any part of the state changes (not recommended, but good for
76
+ fast prototyping).
68
77
 
69
78
  ```tsx
70
79
  function MyComponent() {
71
- const state = useAllState();
80
+ const state = useAllState<State>();
72
81
 
73
- return <div>{state.name} has {state.age} years old</div>;
82
+ return <div>{state.name} is {state.age} years old</div>;
74
83
  };
75
84
  ```
76
85
 
77
86
  The `useSelect` hook selects only the part of the state that your component needs.
78
- It will rebuild only when that part changes.
87
+ The component re-renders only when that part changes.
79
88
 
80
89
  ```tsx
81
90
  function MyComponent() {
82
- const name = useSelect((state) => state.name);
83
- const age = useSelect((state) => state.age);
91
+ const name = useSelect((state: State) => state.name);
92
+ const age = useSelect((state: State) => state.age);
84
93
 
85
- return <div>{name} has {age} years old</div>;
94
+ return <div>{name} is {age} years old</div>;
86
95
  };
87
96
  ```
88
97
 
89
- The `useObject` hook is another alternative that only rebuilds when needed:
98
+ The `useObject` hook also causes the component to re-render only when needed:
90
99
 
91
100
  ```tsx
92
101
  function MyComponent() {
93
102
 
94
- const state = useObject((state) => {
95
- name: state.name,
96
- age: state.age
97
- });
103
+ const state = useObject((state: State) => ({
104
+ name: state.name,
105
+ age: state.age,
106
+ }));
98
107
 
99
- return <div>{state.name} has {state.age} years old</div>;
108
+ return <div>{state.name} is {state.age} years old</div>;
100
109
  };
101
110
  ```
102
111
 
112
+ These hooks connect to the store with React's own
113
+ [`useSyncExternalStore`](https://react.dev/reference/react/useSyncExternalStore),
114
+ so React reads the state itself, compares what each component selected, and renders only
115
+ the components whose selection changed. React also checks the state again before
116
+ committing a
117
+ render it paused (a transition), and renders again if the state changed meanwhile, so a
118
+ screen never shows parts of two different states at the same time.
119
+
103
120
  &nbsp;
104
121
 
105
122
  ## Actions and reducers
106
123
 
107
- An **action** is a class that contain its own **reducer**.
124
+ An **action** is a class with its own **reducer** function.
125
+ This reducer has access to the current state and returns a new state.
108
126
 
109
127
  ```tsx
110
128
  class Increment extends Action {
@@ -120,10 +138,11 @@ class Increment extends Action {
120
138
 
121
139
  ## Dispatch an action
122
140
 
123
- The store state is **immutable**.
141
+ The store's state is **immutable**.
124
142
 
125
- The only way to change the store **state** is by dispatching an **action**.
126
- The action reducer returns a new state, that replaces the old one.
143
+ The only way to change the store's state is by dispatching an **action**,
144
+ wich runs the action's reducer to get a new state.
145
+ The new state replaces the current one, and affected components re-render.
127
146
 
128
147
  ```tsx
129
148
  // Dispatch an action
@@ -137,45 +156,89 @@ await store.dispatchAndWait(new Increment());
137
156
 
138
157
  // Dispatch multiple actions and wait for them to finish
139
158
  await store.dispatchAndWaitAll([new Increment(), new LoadText()]);
159
+
160
+ // Dispatch an action when the state meets a condition
161
+ store.dispatchWhen(new LoadText(), (state) => state.count >= 3);
140
162
  ```
141
163
 
142
164
  &nbsp;
143
165
 
144
166
  ## Components can dispatch actions
145
167
 
146
- The hooks to dispatch actions are `useDispatch` , `useDispatchAll` etc.
168
+ Hooks for dispatching actions include `useDispatch`, `useDispatchAll`, `useDispatchWhen`,
169
+ etc.
147
170
 
148
171
  ```tsx
149
172
  function MyComponent() {
150
173
  const dispatch = useDispatch();
151
174
 
152
175
  return (
153
- <Button onClick={() => dispatch(new LoadText())}>
154
- Click me!
155
- </Button>
176
+ <Button onClick={() => dispatch(new LoadText())}>
177
+ Click me!
178
+ </Button>
156
179
  );
157
180
  };
158
181
  ```
159
182
 
160
- Or getting the store with `useStore` also allows you to dispatch actions:
183
+ You can also get the store with `useStore` and dispatch actions directly:
161
184
 
162
185
  ```tsx
163
186
  function MyComponent() {
164
187
  const store = useStore();
165
188
 
166
189
  return (
167
- <Button onClick={() => store.dispatch(new LoadText())}>
168
- Click me!
169
- </Button>
190
+ <Button onClick={() => store.dispatch(new LoadText())}>
191
+ Click me!
192
+ </Button>
170
193
  );
171
194
  };
172
195
  ```
173
196
 
197
+ To dispatch actions when the component mounts, when some values change, and when it
198
+ unmounts,
199
+ use `useStoreEffect` instead of a `useEffect`:
200
+
201
+ ```tsx
202
+ useStoreEffect({
203
+ deps: userId, // List the dependencies
204
+
205
+ // Loads information needed for this screen
206
+ onMount: (store) => store.dispatch(new LoadUser(userId)),
207
+
208
+ // When the userId changes, stop listening to the old user and load the new one
209
+ onDepsChange: (store, oldUserId) => {
210
+ store.dispatch(new StopListening(oldUserId));
211
+ store.dispatch(new LoadUser(userId));
212
+ },
213
+
214
+ // When the component unmounts, clean up any resources used by this screen
215
+ onUnmount: (store) => store.dispatch(new CleanResources()),
216
+ });
217
+ ```
218
+
219
+ To reload the data on screen when the user comes back to the browser tab, or when the
220
+ internet
221
+ comes back, add `onFocus` and `onOnline` (there are also `onBlur` and `onOffline`). They
222
+ run
223
+ only on the transitions, while the component is mounted, never on mount. Give the action a
224
+ `fresh` period to skip the reload when the data is recent:
225
+
226
+ ```tsx
227
+ useStoreEffect({
228
+ onMount: (store) => store.dispatch(new LoadPrices()),
229
+ onFocus: (store) => store.dispatch(new LoadPrices()),
230
+ onOnline: (store) => store.dispatch(new LoadPrices()),
231
+ });
232
+ ```
233
+
234
+ Also available in components with `useIsFocused()` and `useIsOnline()`,
235
+ for an "offline" banner.
236
+
174
237
  &nbsp;
175
238
 
176
239
  ## Actions can do asynchronous work
177
240
 
178
- They can download information from the internet, or do any other async work.
241
+ Actions can fetch data from the internet or do any other async work.
179
242
 
180
243
  ```tsx
181
244
  const store = createStore<string>({initialState: ''});
@@ -192,19 +255,21 @@ class LoadText extends Action {
192
255
  let text = await response.text();
193
256
 
194
257
  // Change the state with the downloaded information
195
- return (state) => text;
258
+ return (state: string) => text;
196
259
  }
260
+ }
197
261
  ```
198
262
 
199
263
  &nbsp;
200
264
 
201
265
  ## Actions can throw errors
202
266
 
203
- If something bad happens, you can simply **throw an error**. In this case, the state will not
204
- change. Errors are caught globally and can be handled in a central place, later.
267
+ If an error occurs, you can simply **throw it**. In this case, the action will not
268
+ change the state. Errors are caught globally and can be handled later in one central
269
+ place.
205
270
 
206
- In special, if you throw a `UserException`, which is a type provided by Kiss,
207
- a dialog (or other UI) will open automatically, showing the error message to the user.
271
+ If you throw a `UserException` (a type provided by Kiss), a dialog or another UI element
272
+ opens automatically and shows the error message to the user.
208
273
 
209
274
  ```tsx
210
275
  class LoadText extends Action {
@@ -212,26 +277,27 @@ class LoadText extends Action {
212
277
  async reduce() {
213
278
  let response = await fetch("https://dummyjson.com/todos/random/1");
214
279
  if (!response.ok) throw new UserException("Failed to load.");
215
-
216
- let text = await response.text();
217
- return (state) => text;
280
+
281
+ let text = await response.text();
282
+ return (state: string) => text;
218
283
  }
284
+ }
219
285
  ```
220
286
 
221
287
  &nbsp;
222
288
 
223
289
  ## Components can react to actions
224
290
 
225
- To show a spinner while an asynchronous action is running, use `isWaiting(action)`.
291
+ To show a spinner while an asynchronous action is running, use `useIsWaiting(ActionType)`.
226
292
 
227
- To show an error message inside the component, use `isFailed(action)`.
293
+ To show an error message inside the component, use `useIsFailed(ActionType)`.
228
294
 
229
295
  ```tsx
230
296
  function MyComponent() {
231
297
 
232
298
  const isWaiting = useIsWaiting(LoadText);
233
299
  const isFailed = useIsFailed(LoadText);
234
- const state = useAllState();
300
+ const state = useAllState<string>();
235
301
 
236
302
  if (isWaiting) return <CircularProgress />
237
303
  if (isFailed) return <p>Loading failed...</p>;
@@ -239,6 +305,107 @@ function MyComponent() {
239
305
  }
240
306
  ```
241
307
 
308
+ These hooks work per action class: `useIsWaiting(LoadUser)` is true while **any**
309
+ `LoadUser` runs. In a list where each row loads its own user,
310
+ give the action a `statusKey`, and pass the same key to the hooks,
311
+ so that each row sees only its own user:
312
+
313
+ ```tsx
314
+ class LoadUser extends Action {
315
+ constructor(readonly userId: string) { super(); }
316
+ get statusKey() { return this.userId; }
317
+ async reduce() { ... }
318
+ }
319
+
320
+ function UserRow({ userId }: { userId: string }) {
321
+ const isWaiting = useIsWaiting(LoadUser, { statusKey: userId });
322
+ const isFailed = useIsFailed(LoadUser, { statusKey: userId });
323
+ ...
324
+ }
325
+ ```
326
+
327
+ ### Suspense and error boundaries
328
+
329
+ If you prefer React's `<Suspense>` and error boundaries to `isWaiting`/`isFailed` checks,
330
+ use
331
+ `useSuspense` instead. It suspends the component while the action runs, and throws the
332
+ error
333
+ to the nearest error boundary if the action failed:
334
+
335
+ ```tsx
336
+ function UserName({ userId }: { userId: string }) {
337
+ useSuspense(LoadUser, { statusKey: userId });
338
+ const user = useSelect((state: State) => state.users[userId]);
339
+ return <p>{user.name}</p>;
340
+ }
341
+
342
+ function UserCard({ userId }: { userId: string }) {
343
+ return (
344
+ <ErrorBoundary fallback={<p>Loading failed.</p>}>
345
+ <Suspense fallback={<Spinner />}>
346
+ <UserName userId={userId} />
347
+ </Suspense>
348
+ </ErrorBoundary>
349
+ );
350
+ }
351
+ ```
352
+
353
+ &nbsp;
354
+
355
+ ## Actions can send events to the UI
356
+
357
+ Sometimes an action needs the UI to do something **once**, without changing the state.
358
+ For example:
359
+
360
+ * Scroll a list to the top
361
+ * Clear or focus an input
362
+ * Open a dialog
363
+
364
+ The UI keeps track of these things itself (DOM elements, refs, scroll positions).
365
+ They are not part of the global app state, so action reducers can't access them.
366
+
367
+ But you can put **events** (`Evt`) in the state, which actions can modify,
368
+ and then UI components can react to these events with `useEvent`:
369
+
370
+ ```tsx
371
+ class State {
372
+ constructor(
373
+ readonly messages: readonly Message[],
374
+ readonly scrollToTopEvt: Evt, // A boolean event.
375
+ readonly changeTextEvt: Evt<string>, // An event with a value.
376
+ ) {}
377
+
378
+ static initialState = new State([], Evt.spent(), Evt.spent());
379
+ }
380
+
381
+ // Dispatch this action to scroll the list to the top
382
+ class ScrollFeedToTop extends Action {
383
+ reduce() { return this.state.copy({ scrollToTopEvt: new Evt() }); }
384
+ }
385
+
386
+ // Dispatch this action to change the text in an input
387
+ class ChangeText extends Action {
388
+ async reduce() {
389
+ const text = await api.fetchText();
390
+ return (state: State) => state.copy({ changeTextEvt: new Evt(text) });
391
+ }
392
+ }
393
+
394
+ function Feed() {
395
+ const listRef = useRef<HTMLDivElement>(null);
396
+ const inputRef = useRef<HTMLInputElement>(null);
397
+
398
+ // The callbacks below run only once per event, with their values.
399
+
400
+ // Handle the event that scrolls the list
401
+ useEvent((state: State) => state.scrollToTopEvt, () => listRef.current?.scrollTo({ top: 0 }));
402
+
403
+ // Handle the event that changes the input text
404
+ useEvent((state: State) => state.changeTextEvt, (text) => { inputRef.current!.value = text; });
405
+ ...
406
+ }
407
+ ```
408
+
242
409
  &nbsp;
243
410
 
244
411
  ## Actions can dispatch other actions
@@ -253,8 +420,8 @@ class LoadTextAndIncrement extends Action {
253
420
  // Dispatch and wait for the action to finish
254
421
  await this.dispatchAndWait(new LoadText());
255
422
 
256
- // Only then, increment the state
257
- return (state) => state.copy({ count: state.count + 1 });
423
+ // Only then increment the state
424
+ return (state: State) => state.copy({ count: state.count + 1 });
258
425
  }
259
426
  }
260
427
  ```
@@ -272,14 +439,14 @@ class BuyAndSell extends Action {
272
439
  new SellAction('TSLA')
273
440
  ]);
274
441
 
275
- return (state) => state.copy({
276
- message: `New cash balance is ${this.state.cash}`
442
+ return (state: State) => state.copy({
443
+ message: `New cash balance is ${state.cash}`
277
444
  });
278
445
  }
279
446
  }
280
447
  ```
281
448
 
282
- You can also use `waitCondition` to wait until the `state` changes in a certain way:
449
+ You can also use `waitCondition` to wait until the `state` meets a condition:
283
450
 
284
451
  ```tsx
285
452
  class SellStockForPrice extends Action {
@@ -289,75 +456,138 @@ class SellStockForPrice extends Action {
289
456
 
290
457
  // Wait until the stock price is higher than the limit price
291
458
  await this.waitCondition(
292
- (state) => state.stocks.getPrice(this.stock) >= this.price
459
+ (state) => state.stocks.getPrice(this.stock) >= this.price,
460
+ { timeoutMillis: 0 }, // No timeout.
293
461
  );
294
462
 
295
- // Only then, post the sell order to the backend
463
+ // Only then post the sell order to the backend
296
464
  let amount = await postSellOrder(this.stock);
297
465
 
298
- return (state) =>
299
- state.copy(
466
+ return (state: State) =>
467
+ state.copy({
300
468
  stocks: state.stocks.setAmount(this.stock, amount),
301
- );
469
+ });
302
470
  }
303
471
  }
304
472
  ```
305
473
 
306
474
  &nbsp;
307
475
 
308
- ## Add features to your actions
476
+ ## Add "features" to your actions
309
477
 
310
- It's easy to add your own reusable "features" to your actions,
311
- but they come out of the box with some interesting ones:
478
+ ### NonReentrant
312
479
 
313
- ## NonReentrant
314
-
315
- To prevent an action from being dispatched while it's already running,
480
+ To prevent an action from running again while it is already running,
316
481
  add the `nonReentrant` property to your action class and set it to `true`.
317
482
 
318
483
  ```tsx
319
484
  class LoadText extends Action {
320
- nonReentrant = true;
485
+ nonReentrant = true; // Here!
321
486
 
322
487
  reduce() { ... }
323
488
  }
324
489
  ```
325
490
 
326
- ## Retry
491
+ By default, it checks the action class. To let actions of the same class run in parallel
492
+ when they have different parameters, override `nonReentrantKeyParams()`:
493
+
494
+ ```tsx
495
+ class SaveItem extends Action {
496
+ constructor(readonly itemId: string) { super(); }
497
+
498
+ nonReentrant = true;
499
+ nonReentrantKeyParams() { return this.itemId; }
500
+ ...
501
+ }
502
+ ```
503
+
504
+ Now `SaveItem('A')` and `SaveItem('B')` can run in parallel, but two `SaveItem('A')`
505
+ cannot.
327
506
 
328
- If an action fails, to retry it a few times with exponential backoff,
507
+ ### Retry
508
+
509
+ To retry an action a few times with exponential backoff if it fails,
329
510
  add the `retry` property to your action class.
330
511
 
331
512
  ```tsx
332
513
  class LoadText extends Action {
333
- retry = {on: true}
514
+ retry = {on: true} // Here!
334
515
 
335
- reduce() { ... }
516
+ async reduce() { ... }
336
517
  }
337
518
  ```
338
519
 
339
- And you can specify the retry policy:
520
+ Or you can specify the retry policy:
340
521
 
341
522
  ```tsx
342
523
  class LoadText extends Action {
343
524
 
344
525
  retry = {
345
- initialDelay: 350, // Millisecond delay before the first attempt
346
- maxRetries: 3, // Number of retries before giving up
347
- multiplier: 2, // Delay increase factor for each retry
348
- maxDelay: 5000, // Max millisecond delay between retries
526
+ initialDelay: 350, // Delay in milliseconds before the first retry
527
+ maxRetries: 3, // Number of retries before stopping
528
+ multiplier: 2, // Factor used to increase the delay after each retry
529
+ maxDelay: 5000, // Maximum delay between retries, in milliseconds
349
530
  }
350
531
 
351
- reduce() { ... }
532
+ async reduce() { ... }
352
533
  }
353
534
  ```
354
535
 
355
- ## Debounce
536
+ By default, every error is retried.
537
+ To give up on errors that will fail again anyway (like a 404 or a 401),
538
+ override `shouldRetry`.
356
539
 
357
- To limit how often an action occurs in response to rapid inputs, you can add a `debounce` property
358
- to your action class. For example, when a user types in a search bar, debouncing ensures that not
359
- every keystroke triggers a server request. Instead, it waits until the user pauses typing before
360
- acting.
540
+ ```tsx
541
+ class LoadText extends Action {
542
+ retry = {on: true}
543
+
544
+ shouldRetry(error: unknown, attempt: number) {
545
+ return !(error instanceof NotFoundError);
546
+ }
547
+
548
+ async reduce() { ... }
549
+ }
550
+ ```
551
+
552
+ ### CheckInternet
553
+
554
+ To check for an internet connection before running the action, add the `checkInternet`
555
+ property. If there is no internet connection, the action stops. You can also show a dialog
556
+ with the title "There is no Internet", and the message "Please, verify your connection".
557
+
558
+ ```tsx
559
+ class LoadPrices extends Action {
560
+ checkInternet = { dialog: true } // Here!
561
+
562
+ async reduce() { ... }
563
+ }
564
+ ```
565
+
566
+ Use `checkInternet = { dialog: false }` to fail without a dialog, so you can show the
567
+ error in your components with `isFailed`. Or use `checkInternet = { abort: true }` to
568
+ abort the
569
+ action silently, as if it had never been dispatched, without any errors.
570
+
571
+ ### UnlimitedRetryCheckInternet
572
+
573
+ To keep trying an action until it succeeds, add the `unlimitedRetryCheckInternet`
574
+ property. If there is no internet, the action waits, and retries until there is.
575
+ It also retries if there is internet but the action fails.
576
+
577
+ ```tsx
578
+ class LoadPrices extends Action {
579
+ unlimitedRetryCheckInternet = true
580
+
581
+ async reduce() { ... }
582
+ }
583
+ ```
584
+
585
+ ### Debounce
586
+
587
+ To limit how often an action runs in response to rapid input, add a `debounce` property
588
+ to your action class. For example, when a user types into a search bar, debouncing ensures
589
+ that not every keystroke triggers a server request. Instead, the action waits until the
590
+ user stops typing for a short time before running.
361
591
 
362
592
  ```tsx
363
593
  class SearchText extends Action {
@@ -366,86 +596,372 @@ class SearchText extends Action {
366
596
  debounce = 300 // Milliseconds
367
597
 
368
598
  async reduce() {
369
- let result = await loadJson('https://example.com/?q=', searchTerm);
370
- return (state) => state.copy({searchResult: result});
599
+ let result = await loadJson('https://example.com/?q=', this.searchTerm);
600
+ return (state: State) => state.copy({searchResult: result});
371
601
  }
372
602
  }
373
603
  ```
374
604
 
375
- ## Throttle
605
+ ### IgnoreOld
376
606
 
377
- To prevent an action from running too frequently, you can add a `throttle` property to your
378
- action class. This means that once the action runs it's considered _fresh_, and it won't run
379
- again for a set period of time, even if you try to dispatch it.
380
- After this period ends, the action is considered _stale_ and is ready to run again.
607
+ When the same action may be dispatched again before the previous one finishes (for
608
+ example, when the user switches tabs or filters quickly), a slow older request may finish
609
+ last, and overwrite the newer information. To prevent that, add the `ignoreOld` property
610
+ to your action class.
611
+
612
+ You can optionally pass the action's `abortSignal` to `fetch` to cancel requests:
381
613
 
382
614
  ```tsx
383
- class LoadPrices extends Action {
384
-
615
+ class LoadTab extends Action {
616
+ constructor(readonly tab: string) { super(); }
617
+ ignoreOld = true;
618
+
619
+ async reduce() {
620
+ let response = await fetch(`/api/items?tab=${this.tab}`, {signal: this.abortSignal});
621
+ let items = await response.json();
622
+ return (state: State) => state.copy({items});
623
+ }
624
+ }
625
+ ```
626
+
627
+ You can also check `this.isAborted` inside the reducer to know if the action was aborted.
628
+
629
+ ### Aborting actions
630
+
631
+ Call `store.abort(ActionType)` to abort all the actions of that type that are in progress,
632
+ for example, from a "Cancel" button, or when the component that started a request
633
+ unmounts.
634
+
635
+ ```tsx
636
+ useStoreEffect({
637
+ onMount: (store) => store.dispatch(new LoadUser(userId)),
638
+ onUnmount: (store) => store.abort(LoadUser),
639
+ });
640
+ ```
641
+
642
+ ### Throttle
643
+
644
+ To prevent an action from running too frequently, you can add a `throttle` property to
645
+ your action class. The action then runs at most once per throttle period. If you dispatch
646
+ it again during that period, the new dispatch is aborted. After the period ends, the next
647
+ dispatch runs, and starts a new period.
648
+
649
+ ```tsx
650
+ class LoadPrices extends Action {
385
651
  throttle = 5000 // Milliseconds
386
652
 
387
653
  async reduce() {
388
654
  let result = await loadJson('https://example.com/prices');
389
- return (state) => state.copy({prices: result});
655
+ return (state: State) => state.copy({prices: result});
390
656
  }
391
657
  }
392
658
  ```
393
659
 
394
- ## CheckInternet
660
+ Override `ignoreThrottle` to run the action anyway under some conditions (for example,
661
+ a `force` flag).
662
+
663
+ ```tsx
664
+ class LoadPrices extends Action {
665
+ constructor(public force = false) { super(); }
666
+ throttle = 5000;
667
+ get ignoreThrottle() { return this.force; }
668
+ ...
669
+ }
670
+ ```
671
+
672
+ ### Fresh
395
673
 
396
- Automatically checks if there is an internet connection before running the action.
397
- If there is no internet, the action aborts. Optionally, it can show a dialog to the user
398
- saying something like: "There is no Internet, please verify your connection".
674
+ To avoid reloading the same information too often, add a `fresh` property to your action
675
+ class. When the action runs, its result is considered fresh for that period of time,
676
+ and dispatching it again during that period is aborted. After the period ends,
677
+ the data is stale, and the next dispatch runs and starts a new period.
399
678
 
400
679
  ```tsx
401
- class LoadPrices extends Action {
402
-
403
- checkInternet = { dialog: true }
680
+ class LoadPrices extends Action {
681
+ fresh = 5000 // Milliseconds
404
682
 
405
- async reduce() { ... }
683
+ async reduce() {
684
+ let result = await loadJson('https://example.com/prices');
685
+ return (state: State) => state.copy({prices: result});
686
+ }
406
687
  }
407
688
  ```
408
689
 
409
- ## OptimisticUpdate
690
+ ### Sequential
410
691
 
411
- To provide instant feedback on actions that save information to the server, this feature immediately
412
- applies state changes as if they were already successful, before confirming with the server.
413
- If the server update fails, the change is rolled back and, optionally, a notification can inform
414
- the user of the issue.
692
+ To make actions run one at a time, in the exact order they were dispatched, add the
693
+ `sequential` property to your action class and set it to `true`. Each dispatched action
694
+ waits until all the actions dispatched before it have finished.
415
695
 
416
696
  ```tsx
417
- class SaveName extends Action {
418
-
419
- optimisticUpdate = { ... }
697
+ class SaveItem extends Action {
698
+ sequential = true; // Here!
699
+ constructor(readonly item: Item) { super(); }
420
700
 
421
- async reduce() { ... }
701
+ async reduce() {
702
+ await saveItem(this.item);
703
+ return null;
704
+ }
705
+ }
706
+ ```
707
+
708
+ By default, all sequential actions share a single queue, even if they are of different
709
+ classes. To have independent queues, override `sequentialKeyParams()`. Actions with the
710
+ same key run one at a time, while actions with different keys run in parallel:
711
+
712
+ ```tsx
713
+ class SaveUser extends Action {
714
+ sequential = true;
715
+ constructor(readonly userId: string) { super(); }
716
+ sequentialKeyParams() { return this.userId; }
717
+ ...
718
+ }
719
+ ```
720
+
721
+ ### Polling
722
+
723
+ To periodically dispatch an action at a fixed interval, add a `poll` property to your
724
+ action class (usually as a constructor parameter), and override `createPollingAction()` to
725
+ return the action each tick dispatches. Dispatch it with `Poll.start` to run it right away
726
+ and start polling, and with `Poll.stop` to stop polling. Use `Poll.runNowAndRestart` to
727
+ run it now and restart the timer, and `Poll.once` (the default) to run it once, without
728
+ affecting the polling.
729
+
730
+ ```tsx
731
+ class LoadPrices extends Action {
732
+ constructor(readonly poll = Poll.once) { super(); }
733
+ pollInterval = 5000; // Milliseconds
734
+ createPollingAction() { return new LoadPrices(); }
735
+
736
+ async reduce() {
737
+ let result = await loadJson('https://example.com/prices');
738
+ return (state: State) => state.copy({prices: result});
739
+ }
740
+ }
741
+
742
+ dispatch(new LoadPrices(Poll.start)); // Start polling.
743
+ dispatch(new LoadPrices(Poll.stop)); // Stop polling.
744
+ ```
745
+
746
+ Each tick waits for the previous run to finish, so runs never overlap.
747
+ Set `pollWaitsForRun = false` to tick at a fixed rate instead.
748
+
749
+ By default, the ticks only run while the app is focused (in the browser, the tab is
750
+ visible) and online. A tick that comes due while the user is away waits, and runs as soon
751
+ as the user comes back to the tab, or the internet comes back. Set
752
+ `pollOnlyWhenFocused = false` or `pollOnlyWhenOnline = false` to keep polling anyway.
753
+
754
+ To stop all polling at once (for example, on logout), call `stopAllPolling()` from any
755
+ action.
756
+
757
+ ## Advanced Features
758
+
759
+ ### OptimisticCommand
760
+
761
+ To provide instant feedback when an action sends a command to the server (like adding a
762
+ todo, or sending a message), extend `OptimisticCommand`. It changes the state immediately,
763
+ before the server confirms that the command succeeded.
764
+ If the command fails, the state is changed back, and the error is shown to the user.
765
+ It can also reload the value from the server.
766
+
767
+ ### OptimisticSync
768
+
769
+ For rapid toggles (like a "like" button), extend `OptimisticSync`. Every dispatch changes
770
+ the state immediately, but only one request per key is sent to the server at a time.
771
+ When the request finishes, if the state changed meanwhile, a follow-up request sends the
772
+ latest value, until the state stabilizes. This keeps the UI responsive, while minimizing
773
+ server load.
774
+
775
+ ### OptimisticSyncWithPush and ServerPush
776
+
777
+ If your app also receives server pushes (WebSockets, Server-Sent Events, Firebase) that
778
+ may change the same values, and more than one device can change them, extend
779
+ `OptimisticSyncWithPush` instead of `OptimisticSync`, and apply the pushes with an action
780
+ that extends `ServerPush`. They track revisions, so that stale or out-of-order pushes are
781
+ ignored, local changes are not overwritten by older pushes, and the last write wins across
782
+ devices.
783
+
784
+ ### LoadPages
785
+
786
+ To load a list page by page (a "load more" button, or an infinite scroll), extend
787
+ `LoadPages`.
788
+ It keeps the loaded pages in the state, in an immutable `Pages` value, and knows how to
789
+ load the next page, the previous page, the first page again, or all the loaded pages
790
+ again.
791
+
792
+ ## Disposing the store
793
+
794
+ Apps have long-lived things that are not state, and must not go in the state: intervals,
795
+ WebSockets, `EventSource`s, `AbortController`s, listeners (like Firebase's `onSnapshot`,
796
+ which returns an unsubscribe function), RxJS subscriptions.
797
+
798
+ Keep them in the store **props**, with `setProp`, and close them with `disposeProp`:
799
+
800
+ ```tsx
801
+ class StartClock extends Action {
802
+ reduce() {
803
+ const interval = setInterval(() => this.dispatch(new Tick()), 1000);
804
+ this.setProp('clock', interval, { dispose: clearInterval });
805
+ return null;
806
+ }
807
+ }
808
+
809
+ class StopClock extends Action {
810
+ reduce() {
811
+ this.disposeProp('clock');
812
+ return null;
813
+ }
422
814
  }
423
815
  ```
424
816
 
817
+ The props belong to the store, so each test (or each request, in server-side rendering)
818
+ has its own, and they can all be closed at once. Kiss knows how to automatically dispose
819
+ an `AbortController` (aborted), a `WebSocket`, `EventSource`, `BroadcastChannel`,
820
+ `MessagePort` or `Worker` (closed or terminated), an object with `unsubscribe()` (RxJS)
821
+ and an object with `[Symbol.dispose]()` or `[Symbol.asyncDispose]()`.
822
+
823
+ Setting a prop again with the same key disposes the previous value, so dispatching
824
+ `StartClock` twice doesn't leak the first interval. Read a prop with
825
+ `prop(key)`, list them with `props`, and dispose many with `disposeProps(predicate?)`.
826
+
827
+ The same methods exist on the store. On logout, `store.logOut({ disposeProps: true })`
828
+ disposes them too.
829
+
830
+ To end the store, when the app finishes or at the end of each test, call
831
+ `store.dispose()`. It shuts down the store, stops all the action features, cancels the
832
+ waiting `dispatchWhen`s, pauses the persistor, and disposes all the props.
833
+ It returns a promise that waits for the async disposals.
834
+
835
+ &nbsp;
836
+
837
+ ## Environment, dependencies and configuration
838
+
839
+ Inject the services the actions use (API clients, repositories, analytics...) into the
840
+ store, instead of importing them from modules. Each test then creates its own store with
841
+ its own dependencies (fakes, for example), with nothing global to set up or reset, and two
842
+ stores can live side by side (tests running concurrently, or one store per request in
843
+ server-side rendering). The store takes the `environment` (production, staging,
844
+ testing...), a `configuration` factory (feature flags) and a `dependencies` factory. The
845
+ factories get the store, so they can depend on the environment, and the configuration is
846
+ created first, so the dependencies can read it:
847
+
848
+ ```tsx
849
+ const store = createStore<State>({
850
+ initialState: State.initialState,
851
+ environment: Environment.production,
852
+ configuration: (store) => new Config(),
853
+ dependencies: (store) => new Dependencies(store.environment as Environment),
854
+ });
855
+ ```
856
+
857
+ In components, `useEnvironment()` and `useConfiguration()` return the environment and the
858
+ configuration, and never re-render, since the values don't change. Components should
859
+ usually not need the dependencies. The `errorObserver` gets the store, so it can read
860
+ `store.environment`, for example to send the errors to a monitoring service only in
861
+ production.
862
+
863
+ In tests:
864
+
865
+ ```tsx
866
+ const store = createStore<State>({
867
+ initialState: State.initialState,
868
+ environment: Environment.testing,
869
+ dependencies: () => new FakeDependencies(),
870
+ });
871
+ ```
872
+
425
873
  &nbsp;
426
874
 
427
875
  ## Persist the state
428
876
 
429
877
  You can add a `persistor` to save the state to the local device disk.
430
- It supports serializing JavaScript objects **and** ES6 classes out of the box.
878
+ It supports serialization of JavaScript objects **and** ES6 class instances.
431
879
 
432
880
  ```tsx
433
881
  const store = createStore<State>({
434
- persistor: new Persistor(),
882
+ initialState: new State(),
883
+ persistor: new MyPersistor(),
435
884
  });
885
+
886
+ // Wait for the saved state to load, then start the app.
887
+ await store.ready();
888
+ store.dispatch(new InitAppAction());
889
+ ```
890
+
891
+ &nbsp;
892
+
893
+ ## Server-side rendering
894
+
895
+ Kiss works with server-side rendering out of the box: plain Node with `renderToString` or
896
+ streaming, and Next.js with the app router or the pages router. The server renders the HTML
897
+ from the store, the browser hydrates it with no mismatches, and from then on it's a normal
898
+ Kiss app.
899
+
900
+ On the server, create a store per request with `server: true`, load the data with the same
901
+ actions the client uses, render, and dispose the store:
902
+
903
+ ```tsx
904
+ const store = createStore<State>({ initialState: new State(), server: true });
905
+ await store.dispatchAndWait(new LoadData());
906
+ const html = renderToString(
907
+ <StoreProvider store={store} serverState={store.state}>
908
+ <App />
909
+ </StoreProvider>
910
+ );
911
+ const transfer = JSON.stringify(store.state); // Goes in the HTML, for the browser.
912
+ await store.dispose();
436
913
  ```
437
914
 
915
+ In the browser, create the store with the state the server sent, and hydrate with the same
916
+ `StoreProvider`. That's all the setup. What you get:
917
+
918
+ - **No hydration mismatches.** While hydrating, the hooks render the state the server
919
+ rendered, even if a persistor already restored a newer state in the browser. After
920
+ hydration, the components catch up with the live state.
921
+ - **The same actions on both sides.** A `LoadData` that polls, retries or debounces in the
922
+ browser simply runs once in the server store, so a request leaves nothing running in Node.
923
+ - **Next.js, both routers.** A server component (or `getServerSideProps`) loads the data, and
924
+ a client component creates the store once and provides it. Each route gives its own data to
925
+ the store with `StoreSlice`: the HTML shows it, and client-side navigation shows the new
926
+ route's data in its very first render, with no empty or stale frame.
927
+
928
+ ```tsx
929
+ // app/users/[id]/page.tsx, a server component.
930
+ export default async function UserPage({ params }) {
931
+ const user = await fetchUser((await params).id);
932
+ return <StoreSlice state={{ user }} key={user.id}><UserView /></StoreSlice>;
933
+ }
934
+ ```
935
+
936
+ Mutations are ordinary Kiss actions, which call a server action or an API route, so you keep
937
+ `useIsWaiting`, `useIsFailed`, retries and optimistic updates on top of them.
938
+ - **Streaming.** `renderToPipeableStream` and `renderToReadableStream` work, Suspense
939
+ boundaries included.
940
+ - **Nothing half-loaded in the HTML.** On the server, `useIsWaiting` and `useIsFailed` are
941
+ `false`, and `useSuspense` never suspends, so the HTML never shows a spinner or an error.
942
+
943
+ Complete examples, each with a persistor in the browser and Playwright tests that check the
944
+ server HTML, the hydration and the store:
945
+ [Next.js app router](examples/nextjs-app-router),
946
+ [Next.js pages router](examples/nextjs-pages-router),
947
+ [Express with streaming](examples/ssr-express), and a
948
+ [todo app with Next.js](examples/todo-app-nextjs) with a class-based state and the
949
+ `ClassPersistor`. The details (serialization, the persistor, streaming, React Server
950
+ Components) are in the
951
+ [server-side rendering](https://kissforreact.org/react/miscellaneous/server-side-rendering)
952
+ page of the docs.
953
+
438
954
  &nbsp;
439
955
 
440
956
  ## Testing your app is easy
441
957
 
442
958
  Just dispatch actions and wait for them to finish.
443
- Then, verify the new state or check if some error was thrown.
959
+ Then verify the new state or check whether an error occurred.
444
960
 
445
961
  ```tsx
446
962
  class State {
447
963
  constructor(
448
- public items: string[],
964
+ public items: Item[],
449
965
  public selectedItem: number
450
966
  ) {}
451
967
  }
@@ -453,12 +969,12 @@ class State {
453
969
  test('Selecting an item', async () => {
454
970
 
455
971
  const store = createStore<State>({
456
- initialState: new State(['A', 'B', 'C'], -1);
972
+ initialState: new State([{id: 1, text: 'A'}, {id: 2, text: 'B'}, {id: 3, text: 'C'}], -1)
457
973
  });
458
974
 
459
975
  // Should select item 2
460
976
  await store.dispatchAndWait(new SelectItem(2));
461
- expect(store.state.selectedItem).toBe('B');
977
+ expect(store.state.selectedItem).toBe(2);
462
978
 
463
979
  // Fail to select item 42
464
980
  let status = await store.dispatchAndWait(new SelectItem(42));
@@ -470,58 +986,86 @@ test('Selecting an item', async () => {
470
986
 
471
987
  ## Advanced setup
472
988
 
473
- If you are the Team Lead, you set up the app's infrastructure in a central place,
474
- and allow your developers to concentrate solely on the business logic.
989
+ If you are the team lead, you can set up the app's infrastructure in one central place,
990
+ so developers can focus on business logic.
475
991
 
476
- You can add a `stateObserver` to collect app metrics, an `errorObserver` to log errors,
477
- an `actionObserver` to print information to the console during development,
478
- and a `globalWrapError` to catch all errors.
992
+ You can add a `stateObserver` to collect app metrics, an `actionObserver` to log
993
+ information to the console during development, and an `errorObserver` to log errors,
994
+ and to change them before they are handled.
479
995
 
480
996
  ```tsx
481
997
  const store = createStore<string>({
998
+ initialState: '',
482
999
  stateObserver: (action, prevState, newState, error, count) => { ... },
483
- errorObserver: (error, action, store) => { ... }
484
- actionObserver: (action, count, ini) => { ... }
485
- globalWrapError: (error) => { ... }
1000
+ actionObserver: (action, count, ini) => { ... },
1001
+ errorObserver: ({ error, originalError, action, store }) => { ... },
486
1002
  });
487
1003
  ```
488
1004
 
489
- For example, here we handle `FirestoreError` errors thrown by Firebase.
490
- We convert them into `UserException` errors, which are built-in types that
491
- automatically show a message to the user in an error dialog:
1005
+ The `errorObserver` gets all errors thrown by your actions, and also the errors of the
1006
+ persistor (with a `null` action). It returns the error to use: the same one, a different
1007
+ one,
1008
+ or `null` to swallow it. Then, a `UserException` is shown to the user in an error dialog,
1009
+ and
1010
+ any other error is thrown.
1011
+
1012
+ For example, here we convert the `FirestoreError` errors thrown by Firebase into
1013
+ `UserException` errors, which automatically show a message to the user. Other errors are
1014
+ logged, and swallowed in production:
492
1015
 
493
1016
  ```tsx
494
- globalWrapError: (error: any) => {
495
- return (error instanceof FirestoreError)
496
- ? UserException('Error connecting to Firebase')
497
- : error;
498
- }
1017
+ errorObserver: ({ error, action }) => {
1018
+ if (error instanceof FirestoreError)
1019
+ return new UserException('Error connecting to Firebase').withHardCause(error);
1020
+
1021
+ if (error instanceof UserException) return error;
1022
+
1023
+ Logger.error(`Got ${error} in ${action ?? 'the persistor'}.`);
1024
+ return inProduction() ? null : error;
1025
+ }
1026
+ ```
1027
+
1028
+ By default, Kiss logs what it does (for example, each dispatched action) to the console.
1029
+ Use `logger` to send these messages somewhere else, or set it to `null` to turn logging
1030
+ off.
1031
+ With `null`, Kiss doesn't even build the log messages:
1032
+
1033
+ ```tsx
1034
+ const store = createStore<State>({
1035
+ initialState: new State(),
1036
+ logger: (obj) => myLogger.info(obj), // Or `null` to turn logging off.
1037
+ logStateChanges: true, // Also log every state change.
1038
+ });
499
1039
  ```
500
1040
 
501
1041
  &nbsp;
502
1042
 
503
1043
  ## Advanced action configuration
504
1044
 
505
- The Team Lead may create a base action class that all actions will extend, and add some common
506
- functionality to it. For example, add getter shortcuts to important parts of the state,
507
- and selectors to help find information.
1045
+ The team lead can create a base action class that all actions will extend, and add some
1046
+ common
1047
+ functionality to it. For example, the base class can provide getter shortcuts to important
1048
+ parts of the state
1049
+ and helper methods to find information.
508
1050
 
509
1051
  ```tsx
510
1052
  class State {
511
- items: Item[];
512
- selectedItem: number;
1053
+ constructor(
1054
+ public items: Item[],
1055
+ public selectedItem: number
1056
+ ) {}
513
1057
  }
514
1058
 
515
1059
  export abstract class Action extends KissAction<State> {
516
1060
 
517
- // Getter shortcuts
1061
+ // Convenience getters
518
1062
  get items() { return this.state.items; }
519
1063
  get selectedItem() { return this.state.selectedItem; }
520
1064
 
521
1065
  // Selectors
522
- findById(id) { return this.items.find((item) => item.id === id); }
523
- get selectedIndex() { return this.items.indexOf(this.selectedItem); }
524
- searchByText(text) { return this.items.find((item) => item.text.includes(text)); }
1066
+ findById(id: number) { return this.items.find((item) => item.id === id); }
1067
+ get selectedIndex() { return this.items.findIndex((item) => item.id === this.selectedItem); }
1068
+ searchByText(text: string) { return this.items.find((item) => item.text.includes(text)); }
525
1069
  }
526
1070
  ```
527
1071
 
@@ -533,8 +1077,8 @@ class SelectItem extends Action {
533
1077
 
534
1078
  reduce() {
535
1079
  let item = this.findById(this.id);
536
- if (item === undefined) throw new Error('Item not found');
537
- return this.state.copy({selectedItem: item});
1080
+ if (item === undefined) throw new UserException('Item not found');
1081
+ return new State(this.items, item.id);
538
1082
  }
539
1083
  }
540
1084
  ```
@@ -547,6 +1091,5 @@ class SelectItem extends Action {
547
1091
 
548
1092
  * [Kiss GitHub](https://github.com/marcglasberg/kiss-for-react)
549
1093
 
550
- * Created by [Marcelo Glasberg](https://glasberg.dev) ([GitHub](https://github.com/marcglasberg), [LinkedIn](https://www.linkedin.com/in/marcglasberg/))
551
-
552
-
1094
+ * Created by [Marcelo Glasberg](https://glasberg.dev)
1095
+ ([GitHub](https://github.com/marcglasberg), [LinkedIn](https://www.linkedin.com/in/marcglasberg/))