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