@oxog/state 1.2.0 → 1.3.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/README.md +258 -151
- package/dist/iife/index.global.js +1 -47
- package/dist/index.cjs +1126 -933
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +145 -68
- package/dist/index.d.ts +145 -68
- package/dist/index.js +1125 -934
- package/dist/index.js.map +1 -1
- package/package.json +13 -8
package/README.md
CHANGED
|
@@ -8,13 +8,14 @@ Zero-dependency reactive state management for any framework.
|
|
|
8
8
|
|
|
9
9
|
## Features
|
|
10
10
|
|
|
11
|
-
- **Zero Dependencies** - No runtime dependencies
|
|
11
|
+
- **Zero Dependencies** - No runtime dependencies (React is an optional peer for the hooks)
|
|
12
12
|
- **Framework Agnostic** - Works with React, Vue, Svelte, or vanilla JS
|
|
13
|
-
- **TypeScript Native** - Built with strict mode
|
|
13
|
+
- **TypeScript Native** - Built with strict mode; actions are typed from their definitions
|
|
14
14
|
- **Plugin System** - Extend with persist, devtools, history, sync, logger, effects, validate
|
|
15
15
|
- **Slices & Computed** - Modular state organization with derived values
|
|
16
16
|
- **Store Federation** - Combine multiple stores for large applications
|
|
17
|
-
- **
|
|
17
|
+
- **Small** - About 3 KB gzipped for the core store when tree-shaken
|
|
18
|
+
- **ESM, CommonJS and a CDN build** - `import`, `require()` or `<script>` (`window.OxogState`)
|
|
18
19
|
|
|
19
20
|
## Installation
|
|
20
21
|
|
|
@@ -32,44 +33,66 @@ pnpm add @oxog/state
|
|
|
32
33
|
|
|
33
34
|
## Quick Start
|
|
34
35
|
|
|
35
|
-
```
|
|
36
|
+
```tsx
|
|
36
37
|
import { createStore, useStore } from '@oxog/state';
|
|
37
38
|
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
})
|
|
39
|
+
// State plus actions. An action receives the current state (and any
|
|
40
|
+
// arguments) and returns the part of the state to update.
|
|
41
|
+
const store = createStore(
|
|
42
|
+
{ count: 0 },
|
|
43
|
+
{
|
|
44
|
+
increment: (state) => ({ count: state.count + 1 }),
|
|
45
|
+
incrementBy: (state, by: number) => ({ count: state.count + by }),
|
|
46
|
+
}
|
|
47
|
+
);
|
|
44
48
|
|
|
45
49
|
// Use in React
|
|
46
50
|
function Counter() {
|
|
47
51
|
const count = useStore(store, (s) => s.count);
|
|
48
52
|
const increment = useStore(store, (s) => s.increment);
|
|
49
53
|
|
|
50
|
-
return <button onClick={increment}>{count}</button>;
|
|
54
|
+
return <button onClick={() => increment()}>{count}</button>;
|
|
51
55
|
}
|
|
52
56
|
|
|
53
57
|
// Use in vanilla JS
|
|
54
58
|
store.subscribe((state) => console.log(state.count));
|
|
55
|
-
store.getState().increment();
|
|
59
|
+
store.getState().increment(); // actions live on the state...
|
|
60
|
+
store.incrementBy(5); // ...and on the store
|
|
56
61
|
```
|
|
57
62
|
|
|
58
63
|
## API Reference
|
|
59
64
|
|
|
60
65
|
### Core
|
|
61
66
|
|
|
62
|
-
#### `createStore(initialState)`
|
|
67
|
+
#### `createStore(initialState, actions?)`
|
|
63
68
|
|
|
64
|
-
Creates a reactive store.
|
|
69
|
+
Creates a reactive store. Actions can be defined in three ways; each one is
|
|
70
|
+
bound to the store and available both as `store.name(...args)` and as
|
|
71
|
+
`store.getState().name(...args)`.
|
|
65
72
|
|
|
66
73
|
```typescript
|
|
67
|
-
|
|
74
|
+
// Separate actions (recommended in TypeScript: `state` is typed automatically)
|
|
75
|
+
const counter = createStore(
|
|
76
|
+
{ count: 0 },
|
|
77
|
+
{ increment: (state) => ({ count: state.count + 1 }) }
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
// Inline actions, prefixed with $ (the $ is dropped from the name)
|
|
81
|
+
const inline = createStore({
|
|
68
82
|
count: 0,
|
|
69
|
-
$increment: (state) => ({ count: state.count + 1 }),
|
|
83
|
+
$increment: (state: { count: number }) => ({ count: state.count + 1 }),
|
|
70
84
|
});
|
|
85
|
+
inline.increment();
|
|
86
|
+
|
|
87
|
+
// Fluent builder
|
|
88
|
+
const fluent = createStore({ count: 0 })
|
|
89
|
+
.action('increment', (state) => ({ count: state.count + 1 }));
|
|
90
|
+
fluent.increment();
|
|
71
91
|
```
|
|
72
92
|
|
|
93
|
+
An action that returns nothing (`undefined`) does not update the state or
|
|
94
|
+
notify subscribers.
|
|
95
|
+
|
|
73
96
|
#### `batch(fn)`
|
|
74
97
|
|
|
75
98
|
Batch multiple updates into a single notification.
|
|
@@ -87,19 +110,31 @@ batch(() => {
|
|
|
87
110
|
|
|
88
111
|
| Method | Description |
|
|
89
112
|
|--------|-------------|
|
|
90
|
-
| `getState()` | Get current state |
|
|
91
|
-
| `setState(partial)` |
|
|
113
|
+
| `getState()` | Get the current state |
|
|
114
|
+
| `setState(partial)` | Shallow-merge a partial object (or the result of `(state) => partial`) |
|
|
92
115
|
| `merge(partial)` | Deep merge state |
|
|
93
|
-
| `reset()` | Reset to initial state |
|
|
94
|
-
| `subscribe(listener,
|
|
95
|
-
| `
|
|
96
|
-
| `
|
|
116
|
+
| `reset()` | Reset to the initial state |
|
|
117
|
+
| `subscribe(listener)` | Call `listener(state, prevState)` on every change |
|
|
118
|
+
| `subscribe(selector, listener, equalityFn?)` | Call `listener(value, prevValue)` when the selected value changes (default equality: shallow) |
|
|
119
|
+
| `use(plugin)` | Add a plugin |
|
|
120
|
+
| `destroy()` | Clean up the store and its plugins |
|
|
121
|
+
|
|
122
|
+
Notes on subscriber semantics:
|
|
123
|
+
|
|
124
|
+
- A listener that throws is reported (`console.error('Store error:', …)` and the
|
|
125
|
+
plugins' `onError`) and does not stop the other listeners.
|
|
126
|
+
- A `setState` called from inside a listener is delivered after the current
|
|
127
|
+
notification pass, so every listener sees the changes in order and ends on
|
|
128
|
+
the latest state.
|
|
129
|
+
- A listener added during a notification is first called for the next change.
|
|
130
|
+
- `getState()` returns the live state object. Treat it as read-only: mutating
|
|
131
|
+
it bypasses subscribers. Use `setState`, `merge` or the `immer` plugin.
|
|
97
132
|
|
|
98
133
|
### React Hooks
|
|
99
134
|
|
|
100
135
|
#### `useStore(store, selector?, equalityFn?)`
|
|
101
136
|
|
|
102
|
-
Subscribe to store state in React components.
|
|
137
|
+
Subscribe to store state in React components (built on `useSyncExternalStore`).
|
|
103
138
|
|
|
104
139
|
```typescript
|
|
105
140
|
// Full state
|
|
@@ -108,34 +143,35 @@ const state = useStore(store);
|
|
|
108
143
|
// With selector
|
|
109
144
|
const count = useStore(store, (s) => s.count);
|
|
110
145
|
|
|
111
|
-
// With custom equality
|
|
112
|
-
const user = useStore(store, (s) => s.user,
|
|
146
|
+
// With custom equality: no re-render while the user id stays the same
|
|
147
|
+
const user = useStore(store, (s) => s.user, (a, b) => a?.id === b?.id);
|
|
113
148
|
```
|
|
114
149
|
|
|
150
|
+
Selectors may return new objects or arrays: the result is compared with the
|
|
151
|
+
equality function (shallow by default) and the previous value is reused when
|
|
152
|
+
equal, so this does not cause extra renders or render loops.
|
|
153
|
+
|
|
115
154
|
#### `useShallow(selector)` <sup>v1.2</sup>
|
|
116
155
|
|
|
117
|
-
Wrap selectors returning objects
|
|
156
|
+
Wrap selectors returning objects so the same reference is returned while the
|
|
157
|
+
values are shallowly equal.
|
|
118
158
|
|
|
119
159
|
```typescript
|
|
120
160
|
import { useStore, useShallow } from '@oxog/state';
|
|
121
161
|
|
|
122
|
-
|
|
123
|
-
// const data = useStore(store, s => ({ a: s.a, b: s.b }));
|
|
124
|
-
|
|
125
|
-
// With useShallow - only re-renders when values change
|
|
126
|
-
const data = useStore(store, useShallow(s => ({ a: s.a, b: s.b })));
|
|
162
|
+
const data = useStore(store, useShallow((s) => ({ a: s.a, b: s.b })));
|
|
127
163
|
```
|
|
128
164
|
|
|
129
165
|
#### `useStoreSelector(store, selectors)` <sup>v1.2</sup>
|
|
130
166
|
|
|
131
|
-
Select multiple values with
|
|
167
|
+
Select multiple values with named selectors.
|
|
132
168
|
|
|
133
169
|
```typescript
|
|
134
170
|
import { useStoreSelector } from '@oxog/state';
|
|
135
171
|
|
|
136
172
|
const { userCount, totalRevenue } = useStoreSelector(store, {
|
|
137
|
-
userCount: s => s.users.length,
|
|
138
|
-
totalRevenue: s => s.orders.reduce((sum, o) => sum + o.total, 0),
|
|
173
|
+
userCount: (s) => s.users.length,
|
|
174
|
+
totalRevenue: (s) => s.orders.reduce((sum, o) => sum + o.total, 0),
|
|
139
175
|
});
|
|
140
176
|
```
|
|
141
177
|
|
|
@@ -146,39 +182,34 @@ Get multiple actions with stable references.
|
|
|
146
182
|
```typescript
|
|
147
183
|
import { useStoreActions } from '@oxog/state';
|
|
148
184
|
|
|
149
|
-
const { increment, decrement
|
|
150
|
-
store,
|
|
151
|
-
'increment', 'decrement', 'reset'
|
|
152
|
-
);
|
|
185
|
+
const { increment, decrement } = useStoreActions(store, 'increment', 'decrement');
|
|
153
186
|
```
|
|
154
187
|
|
|
155
188
|
#### `useSetState(store)` <sup>v1.2</sup>
|
|
156
189
|
|
|
157
190
|
Get a stable setState function for partial updates.
|
|
158
191
|
|
|
159
|
-
```
|
|
192
|
+
```tsx
|
|
160
193
|
import { useSetState } from '@oxog/state';
|
|
161
194
|
|
|
162
195
|
function Form() {
|
|
163
196
|
const setState = useSetState(store);
|
|
164
197
|
|
|
165
|
-
return (
|
|
166
|
-
<input onChange={(e) => setState({ name: e.target.value })} />
|
|
167
|
-
);
|
|
198
|
+
return <input onChange={(e) => setState({ name: e.target.value })} />;
|
|
168
199
|
}
|
|
169
200
|
```
|
|
170
201
|
|
|
171
|
-
#### `useTransientSubscribe(store, selector, callback)` <sup>v1.2</sup>
|
|
202
|
+
#### `useTransientSubscribe(store, selector, callback, equalityFn?)` <sup>v1.2</sup>
|
|
172
203
|
|
|
173
204
|
Subscribe to state changes without causing re-renders.
|
|
174
205
|
|
|
175
|
-
```
|
|
206
|
+
```tsx
|
|
176
207
|
import { useTransientSubscribe } from '@oxog/state';
|
|
177
208
|
|
|
178
209
|
function Analytics() {
|
|
179
210
|
useTransientSubscribe(
|
|
180
211
|
store,
|
|
181
|
-
s => s.pageViews,
|
|
212
|
+
(s) => s.pageViews,
|
|
182
213
|
(views) => analytics.track('page_view', { count: views })
|
|
183
214
|
);
|
|
184
215
|
|
|
@@ -188,12 +219,12 @@ function Analytics() {
|
|
|
188
219
|
|
|
189
220
|
#### `useCreateStore(initialState)`
|
|
190
221
|
|
|
191
|
-
Create a store scoped to component lifecycle.
|
|
222
|
+
Create a store scoped to the component lifecycle.
|
|
192
223
|
|
|
193
224
|
```typescript
|
|
194
225
|
function MyComponent() {
|
|
195
226
|
const store = useCreateStore({ count: 0 });
|
|
196
|
-
//
|
|
227
|
+
// The store is destroyed after the component unmounts (StrictMode safe)
|
|
197
228
|
}
|
|
198
229
|
```
|
|
199
230
|
|
|
@@ -209,55 +240,64 @@ const increment = useAction(store, 'increment');
|
|
|
209
240
|
|
|
210
241
|
### Slices
|
|
211
242
|
|
|
212
|
-
Organize state into modular
|
|
243
|
+
Organize state into modular slices. A slice creator receives `set` and `get`
|
|
244
|
+
and returns state values and action functions.
|
|
213
245
|
|
|
214
246
|
```typescript
|
|
215
|
-
import {
|
|
247
|
+
import { createSlice, combineSlices, resetSlices } from '@oxog/state';
|
|
216
248
|
|
|
217
|
-
const userSlice = createSlice('user', {
|
|
249
|
+
const userSlice = createSlice('user', (set) => ({
|
|
218
250
|
name: '',
|
|
219
251
|
email: '',
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
});
|
|
252
|
+
login: (name: string, email: string) => set({ name, email }),
|
|
253
|
+
logout: () => set({ name: '', email: '' }),
|
|
254
|
+
}));
|
|
223
255
|
|
|
224
|
-
const cartSlice = createSlice('cart', {
|
|
225
|
-
items: [],
|
|
226
|
-
|
|
227
|
-
});
|
|
256
|
+
const cartSlice = createSlice('cart', (set, get) => ({
|
|
257
|
+
items: [] as string[],
|
|
258
|
+
addItem: (item: string) => set({ items: [...get().items, item] }),
|
|
259
|
+
}));
|
|
228
260
|
|
|
229
|
-
const store =
|
|
230
|
-
...userSlice,
|
|
231
|
-
...cartSlice,
|
|
232
|
-
});
|
|
261
|
+
const store = combineSlices(userSlice, cartSlice);
|
|
233
262
|
|
|
234
|
-
|
|
235
|
-
|
|
263
|
+
store.login('John', 'john@example.com');
|
|
264
|
+
store.addItem('book');
|
|
265
|
+
store.getState().name; // 'John'
|
|
266
|
+
|
|
267
|
+
resetSlices(store, 'cart'); // resets only the cart slice
|
|
236
268
|
```
|
|
237
269
|
|
|
270
|
+
`createNamespacedSlice(namespace, creator)` keeps a slice's state under
|
|
271
|
+
`state[namespace]`; `extendStore(store, ...slices)` adds slices to an existing
|
|
272
|
+
store.
|
|
273
|
+
|
|
238
274
|
### Computed Values
|
|
239
275
|
|
|
240
|
-
Derive values from
|
|
276
|
+
Derive memoized values from a store.
|
|
241
277
|
|
|
242
278
|
```typescript
|
|
243
279
|
import { createStore, computed } from '@oxog/state';
|
|
244
280
|
|
|
245
281
|
const store = createStore({
|
|
246
282
|
items: [{ price: 10, qty: 2 }, { price: 20, qty: 1 }],
|
|
247
|
-
|
|
248
|
-
totalItems: computed((state) =>
|
|
249
|
-
state.items.reduce((sum, i) => sum + i.qty, 0)
|
|
250
|
-
),
|
|
251
|
-
|
|
252
|
-
totalPrice: computed((state) =>
|
|
253
|
-
state.items.reduce((sum, i) => sum + i.price * i.qty, 0)
|
|
254
|
-
),
|
|
255
283
|
});
|
|
256
284
|
|
|
257
|
-
|
|
258
|
-
|
|
285
|
+
const totalItems = computed(store, (state) =>
|
|
286
|
+
state.items.reduce((sum, i) => sum + i.qty, 0)
|
|
287
|
+
);
|
|
288
|
+
const totalPrice = computed(store, (state) =>
|
|
289
|
+
state.items.reduce((sum, i) => sum + i.price * i.qty, 0)
|
|
290
|
+
);
|
|
291
|
+
|
|
292
|
+
console.log(totalItems()); // 3
|
|
293
|
+
console.log(totalPrice()); // 40
|
|
294
|
+
totalPrice.subscribe((value, prev) => console.log(`total ${prev} -> ${value}`));
|
|
259
295
|
```
|
|
260
296
|
|
|
297
|
+
Reading a computed value is always up to date, also from inside another
|
|
298
|
+
store listener. `combineComputed([a, b], ([a, b]) => …)` derives from several
|
|
299
|
+
computed values without observing a half-updated combination.
|
|
300
|
+
|
|
261
301
|
### Store Federation
|
|
262
302
|
|
|
263
303
|
Combine multiple stores into a unified interface.
|
|
@@ -266,7 +306,7 @@ Combine multiple stores into a unified interface.
|
|
|
266
306
|
import { createStore, createFederation } from '@oxog/state';
|
|
267
307
|
|
|
268
308
|
const userStore = createStore({ name: 'John' });
|
|
269
|
-
const cartStore = createStore({ items: [] });
|
|
309
|
+
const cartStore = createStore({ items: [] as string[] });
|
|
270
310
|
const settingsStore = createStore({ theme: 'dark' });
|
|
271
311
|
|
|
272
312
|
const federation = createFederation({
|
|
@@ -279,78 +319,114 @@ const federation = createFederation({
|
|
|
279
319
|
const state = federation.getState();
|
|
280
320
|
console.log(state.user.name, state.cart.items, state.settings.theme);
|
|
281
321
|
|
|
282
|
-
// Subscribe to
|
|
322
|
+
// Subscribe to one store
|
|
283
323
|
federation.subscribeStore('user', (userState) => {
|
|
284
324
|
console.log('User changed:', userState);
|
|
285
325
|
});
|
|
326
|
+
|
|
327
|
+
// Subscribe to all stores
|
|
328
|
+
federation.subscribe((state, prevState, changedStore) => {
|
|
329
|
+
console.log(`${String(changedStore)} changed`);
|
|
330
|
+
});
|
|
286
331
|
```
|
|
287
332
|
|
|
288
333
|
## Plugins
|
|
289
334
|
|
|
290
335
|
### Persist
|
|
291
336
|
|
|
292
|
-
Persist state to localStorage
|
|
337
|
+
Persist state to `localStorage` (the default) or any storage with
|
|
338
|
+
`getItem`/`setItem`/`removeItem`.
|
|
293
339
|
|
|
294
340
|
```typescript
|
|
295
|
-
import { persist } from '@oxog/state';
|
|
341
|
+
import { createStore, persist } from '@oxog/state';
|
|
296
342
|
|
|
297
343
|
const store = createStore({ count: 0, temp: '' })
|
|
298
344
|
.use(persist({
|
|
299
345
|
key: 'my-app',
|
|
300
346
|
storage: localStorage,
|
|
301
|
-
// v1.2.0 options
|
|
302
347
|
version: 1,
|
|
303
|
-
migrate: (state, version) => state,
|
|
348
|
+
migrate: (state, version) => state as { count: number; temp: string },
|
|
304
349
|
partialize: (state) => ({ count: state.count }), // Only persist count
|
|
305
350
|
writeDebounce: 100,
|
|
306
351
|
onRehydrateStorage: (state) => console.log('Hydrated:', state),
|
|
352
|
+
onPersistError: (error) => console.warn('Could not save state', error),
|
|
307
353
|
}));
|
|
308
354
|
```
|
|
309
355
|
|
|
356
|
+
Hydration ignores `__proto__` keys in stored data, corrupt stored data is
|
|
357
|
+
reported through `onPersistError` (or `console.error`) instead of throwing,
|
|
358
|
+
and write errors such as a full storage quota are reported the same way.
|
|
359
|
+
Without `window` (SSR) the default storage does nothing.
|
|
360
|
+
|
|
310
361
|
### DevTools
|
|
311
362
|
|
|
312
|
-
Connect to Redux DevTools Extension.
|
|
363
|
+
Connect to the Redux DevTools Extension. Without the extension the plugin does
|
|
364
|
+
nothing.
|
|
313
365
|
|
|
314
366
|
```typescript
|
|
315
|
-
import { devtools } from '@oxog/state';
|
|
367
|
+
import { createStore, devtools } from '@oxog/state';
|
|
316
368
|
|
|
317
369
|
const store = createStore({ count: 0 })
|
|
318
370
|
.use(devtools({ name: 'My Store' }));
|
|
319
371
|
```
|
|
320
372
|
|
|
373
|
+
Time travel (jump, commit, rollback, reset) applies the state DevTools sends.
|
|
374
|
+
|
|
321
375
|
### History
|
|
322
376
|
|
|
323
377
|
Add undo/redo functionality.
|
|
324
378
|
|
|
325
379
|
```typescript
|
|
326
|
-
import { history } from '@oxog/state';
|
|
380
|
+
import { createStore, history, hasHistory } from '@oxog/state';
|
|
327
381
|
|
|
328
382
|
const store = createStore({ count: 0 })
|
|
329
383
|
.use(history({ limit: 50 }));
|
|
330
384
|
|
|
331
385
|
store.setState({ count: 1 });
|
|
332
386
|
store.setState({ count: 2 });
|
|
333
|
-
store
|
|
334
|
-
store.
|
|
387
|
+
if (hasHistory(store)) {
|
|
388
|
+
store.undo(); // { count: 1 }
|
|
389
|
+
store.redo(); // { count: 2 }
|
|
390
|
+
}
|
|
335
391
|
```
|
|
336
392
|
|
|
337
393
|
### Sync
|
|
338
394
|
|
|
339
|
-
Synchronize state across browser tabs.
|
|
395
|
+
Synchronize state across browser tabs (BroadcastChannel). Every local change is
|
|
396
|
+
sent to the other tabs; when the plugin is installed the current state is
|
|
397
|
+
broadcast once. Action functions are not sent.
|
|
340
398
|
|
|
341
399
|
```typescript
|
|
342
|
-
import { sync } from '@oxog/state';
|
|
400
|
+
import { createStore, sync } from '@oxog/state';
|
|
343
401
|
|
|
344
402
|
const store = createStore({ count: 0 })
|
|
345
403
|
.use(sync({ channel: 'my-app' }));
|
|
346
404
|
```
|
|
347
405
|
|
|
406
|
+
### Immer-style updates
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
import { createStore, immer, produce } from '@oxog/state';
|
|
410
|
+
|
|
411
|
+
const store = createStore({ todos: [{ text: 'a', done: false }] }).use(immer());
|
|
412
|
+
|
|
413
|
+
// With the plugin, setState also accepts a recipe that mutates a draft
|
|
414
|
+
// (in TypeScript, cast setState or use produce directly).
|
|
415
|
+
store.setState(produce(store.getState(), (draft) => {
|
|
416
|
+
for (const todo of draft.todos) todo.done = true;
|
|
417
|
+
draft.todos.push({ text: 'b', done: false });
|
|
418
|
+
}));
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
`produce` copies only what changed (untouched branches keep their identity) and
|
|
422
|
+
never mutates the base state.
|
|
423
|
+
|
|
348
424
|
### Logger <sup>v1.2</sup>
|
|
349
425
|
|
|
350
426
|
Development logging with diff, timestamps, and filtering.
|
|
351
427
|
|
|
352
428
|
```typescript
|
|
353
|
-
import { logger } from '@oxog/state';
|
|
429
|
+
import { createStore, logger } from '@oxog/state';
|
|
354
430
|
|
|
355
431
|
const store = createStore({ count: 0 })
|
|
356
432
|
.use(logger({
|
|
@@ -358,40 +434,49 @@ const store = createStore({ count: 0 })
|
|
|
358
434
|
collapsed: true,
|
|
359
435
|
diff: true,
|
|
360
436
|
timestamp: true,
|
|
361
|
-
filter: (
|
|
437
|
+
filter: (state, prevState) => state.count > 0,
|
|
362
438
|
}));
|
|
363
439
|
```
|
|
364
440
|
|
|
365
441
|
### Effects <sup>v1.2</sup>
|
|
366
442
|
|
|
367
|
-
Reactive side effects with debounce and
|
|
443
|
+
Reactive side effects with debounce, cleanup and cancellation.
|
|
368
444
|
|
|
369
445
|
```typescript
|
|
370
|
-
import { effects, createEffect } from '@oxog/state';
|
|
446
|
+
import { createStore, effects, createEffect } from '@oxog/state';
|
|
371
447
|
|
|
372
448
|
const store = createStore({
|
|
373
449
|
searchTerm: '',
|
|
374
|
-
results: [],
|
|
450
|
+
results: [] as string[],
|
|
375
451
|
})
|
|
376
452
|
.use(effects({
|
|
377
|
-
|
|
378
|
-
(
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
453
|
+
effects: [
|
|
454
|
+
createEffect(
|
|
455
|
+
'search',
|
|
456
|
+
(state) => state.searchTerm,
|
|
457
|
+
async (term, _prev, { setState, signal }) => {
|
|
458
|
+
const res = await fetch(`/api/search?q=${term}`, { signal });
|
|
459
|
+
const results = await res.json();
|
|
460
|
+
setState({ results });
|
|
461
|
+
},
|
|
462
|
+
{ debounce: 300 }
|
|
463
|
+
),
|
|
464
|
+
],
|
|
386
465
|
}));
|
|
387
466
|
```
|
|
388
467
|
|
|
468
|
+
When the selected value changes again, the previous run becomes inactive: its
|
|
469
|
+
`signal` is aborted, `isActive()` returns `false`, and its `setState` calls are
|
|
470
|
+
ignored, so a slow earlier request cannot overwrite a newer result. Cleanup
|
|
471
|
+
functions returned by an effect run before the next run and when the store is
|
|
472
|
+
destroyed.
|
|
473
|
+
|
|
389
474
|
### Validate <sup>v1.2</sup>
|
|
390
475
|
|
|
391
476
|
Schema-agnostic validation with Zod, Yup, or custom validators.
|
|
392
477
|
|
|
393
478
|
```typescript
|
|
394
|
-
import { validate } from '@oxog/state';
|
|
479
|
+
import { createStore, validate, type ValidationAPI } from '@oxog/state';
|
|
395
480
|
import { z } from 'zod';
|
|
396
481
|
|
|
397
482
|
const schema = z.object({
|
|
@@ -402,64 +487,68 @@ const schema = z.object({
|
|
|
402
487
|
const store = createStore({ email: '', age: 0 })
|
|
403
488
|
.use(validate({
|
|
404
489
|
schema,
|
|
405
|
-
|
|
406
|
-
rejectInvalid: true,
|
|
490
|
+
on: 'change', // validate after every change ('manual': only on validate())
|
|
407
491
|
onError: (errors) => console.error(errors),
|
|
408
492
|
}));
|
|
493
|
+
|
|
494
|
+
const validation = store as typeof store & ValidationAPI;
|
|
495
|
+
validation.validate(); // { valid, errors }
|
|
496
|
+
validation.isValid();
|
|
409
497
|
```
|
|
410
498
|
|
|
499
|
+
Validation runs after the state has changed; it reports errors but does not
|
|
500
|
+
reject updates. `throwOnError: true` makes `validate()` throw.
|
|
501
|
+
|
|
411
502
|
## Async Actions
|
|
412
503
|
|
|
413
|
-
|
|
504
|
+
Actions can be async: the resolved partial state is applied.
|
|
414
505
|
|
|
415
506
|
```typescript
|
|
416
|
-
const store = createStore({
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
error: null
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
} catch (error) {
|
|
427
|
-
return { error, loading: false };
|
|
428
|
-
}
|
|
429
|
-
},
|
|
507
|
+
const store = createStore({ data: null as unknown, loading: false, error: null as unknown });
|
|
508
|
+
|
|
509
|
+
const api = store.action('fetch', async (_state, url: string) => {
|
|
510
|
+
store.setState({ loading: true, error: null });
|
|
511
|
+
try {
|
|
512
|
+
const res = await fetch(url);
|
|
513
|
+
return { data: await res.json(), loading: false };
|
|
514
|
+
} catch (error) {
|
|
515
|
+
return { error, loading: false };
|
|
516
|
+
}
|
|
430
517
|
});
|
|
431
518
|
|
|
432
|
-
await
|
|
519
|
+
await api.fetch('/api/users'); // also available as store.getState().fetch(...)
|
|
433
520
|
```
|
|
434
521
|
|
|
522
|
+
The `state` argument is the state when the action was called. If an async
|
|
523
|
+
action can run concurrently, read `store.getState()` after `await`, or guard
|
|
524
|
+
against out-of-order results (the `effects` plugin does this for you).
|
|
525
|
+
|
|
435
526
|
## TypeScript
|
|
436
527
|
|
|
437
|
-
|
|
528
|
+
Types are inferred from the initial state and the actions.
|
|
438
529
|
|
|
439
530
|
```typescript
|
|
440
|
-
import { createStore,
|
|
441
|
-
|
|
442
|
-
// Type inference from slices
|
|
443
|
-
const counterSlice = createSlice('counter', {
|
|
444
|
-
count: 0,
|
|
445
|
-
$increment: (state) => ({ count: state.count + 1 }),
|
|
446
|
-
});
|
|
531
|
+
import { createStore, type Store } from '@oxog/state';
|
|
447
532
|
|
|
448
|
-
|
|
449
|
-
|
|
533
|
+
interface User {
|
|
534
|
+
id: number;
|
|
535
|
+
name: string;
|
|
536
|
+
}
|
|
450
537
|
|
|
451
|
-
// Explicit types
|
|
452
538
|
interface State {
|
|
453
539
|
count: number;
|
|
454
540
|
user: User | null;
|
|
455
541
|
}
|
|
456
542
|
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
543
|
+
const initialState: State = { count: 0, user: null };
|
|
544
|
+
|
|
545
|
+
const store = createStore(initialState, {
|
|
546
|
+
increment: (s) => ({ count: s.count + 1 }),
|
|
547
|
+
setUser: (_s, user: User) => ({ user }),
|
|
462
548
|
});
|
|
549
|
+
|
|
550
|
+
store.setUser({ id: 1, name: 'Ada' }); // typed arguments
|
|
551
|
+
const plain: Store<State> = createStore<State>({ count: 0, user: null });
|
|
463
552
|
```
|
|
464
553
|
|
|
465
554
|
## Testing <sup>v1.2</sup>
|
|
@@ -467,29 +556,47 @@ const store = createStore<State>({
|
|
|
467
556
|
Testing utilities for stores.
|
|
468
557
|
|
|
469
558
|
```typescript
|
|
470
|
-
import { createTestStore,
|
|
559
|
+
import { createTestStore, spyOnStore, mockAction, snapshot } from '@oxog/state';
|
|
471
560
|
|
|
472
|
-
// Isolated test store
|
|
473
|
-
const store = createTestStore({
|
|
474
|
-
count: 0,
|
|
475
|
-
$increment: (s) => ({ count: s.count + 1 }),
|
|
561
|
+
// Isolated test store with a spy and assertions
|
|
562
|
+
const { store, spy, assert, destroy } = createTestStore({
|
|
563
|
+
initialState: { count: 0 },
|
|
476
564
|
});
|
|
565
|
+
store.setState({ count: 1 });
|
|
566
|
+
assert.toEqual({ count: 1 });
|
|
567
|
+
spy?.changes.length; // 1
|
|
477
568
|
|
|
478
|
-
//
|
|
479
|
-
const
|
|
480
|
-
|
|
481
|
-
expect(mock.actionCalls.increment).toBe(1);
|
|
569
|
+
// Spy on an existing store
|
|
570
|
+
const otherSpy = spyOnStore(store);
|
|
571
|
+
await otherSpy.waitFor((s) => s.count > 1);
|
|
482
572
|
|
|
483
|
-
//
|
|
484
|
-
const
|
|
485
|
-
|
|
573
|
+
// Track calls
|
|
574
|
+
const increment = mockAction((n: number) => n + 1);
|
|
575
|
+
increment(1);
|
|
576
|
+
increment.callCount; // 1
|
|
577
|
+
|
|
578
|
+
// JSON snapshot of the state
|
|
579
|
+
expect(snapshot(store)).toMatchSnapshot();
|
|
580
|
+
destroy();
|
|
486
581
|
```
|
|
487
582
|
|
|
583
|
+
## CDN
|
|
584
|
+
|
|
585
|
+
```html
|
|
586
|
+
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
|
|
587
|
+
<script src="https://unpkg.com/@oxog/state/dist/iife/index.global.js"></script>
|
|
588
|
+
<script>
|
|
589
|
+
const store = OxogState.createStore({ count: 0 });
|
|
590
|
+
</script>
|
|
591
|
+
```
|
|
592
|
+
|
|
593
|
+
React is only needed for the hooks; the global build uses `window.React`.
|
|
594
|
+
|
|
488
595
|
## Browser Support
|
|
489
596
|
|
|
490
|
-
- Chrome
|
|
491
|
-
- Firefox
|
|
492
|
-
- Safari 12+
|
|
597
|
+
- Chrome 66+
|
|
598
|
+
- Firefox 57+
|
|
599
|
+
- Safari 12.1+
|
|
493
600
|
- Edge 79+
|
|
494
601
|
|
|
495
602
|
## Documentation
|