add reactions to the tutorial

This commit is contained in:
Yanick Champoux 2022-08-30 14:15:47 -04:00
parent 702a3e76d4
commit fbe624a14c
2 changed files with 88 additions and 0 deletions

View File

@ -0,0 +1,40 @@
import { test, expect } from 'vitest';
import u from 'updeep';
import { Updux } from '../src/index.js';
const todos = new Updux({
initial: [],
actions: {
setNbrTodos: null,
addTodo: null,
},
mutations: {
addTodo: todo => todos => [ ...todos, todo ],
},
reactions: [
({dispatch}) => todos => dispatch.setNbrTodos(todos.length)
],
});
const myDux = new Updux({
initial: {
nbrTodos: 0
},
subduxes: {
todos,
},
mutations: {
setNbrTodos: nbrTodos => u({ nbrTodos })
}
})
test( "basic tests", async () => {
const store = myDux.createStore();
store.dispatch.addTodo('one');
store.dispatch.addTodo('two');
expect(store.getState().nbrTodos).toEqual(2);
});

View File

@ -352,5 +352,53 @@ Note that the `getNextId` selector still gets the
right value; when aggregating subduxes selectors Updux auto-wraps them to
access the right slice of the top object. ```
## Reactions
Reactions -- aka Redux's subscriptions -- can be added to a updux store via the initial config
or the method `addSubscription`. The signature of a reaction is:
```
(storeApi) => (state, previousState, unsubscribe) => {
...
}
```
Subscriptions registered for an updux and its subduxes are automatically
subscribed to the store when calling `createStore`.
The `state` passed to the subscriptions of the subduxes is the local state.
Also, all subscriptions are wrapped such that they are called only if the
local `state` changed since their last invocation.
Example:
```
const todos = new Updux({
initial: [],
actions: {
setNbrTodos: null,
}
reactions: [
({dispatch}) => todos => dispatch.setNbrTodos(todos.length);
],
});
const myDux = new Updux({
initial: {
nbr_todos: 0
},
subduxes: {
todos,
},
mutations: {
setNbrTodos: nbrTodos => u({ nbrTodos })
}
})
```
[immer]: https://www.npmjs.com/package/immer
[lodash]: https://www.npmjs.com/package/lodash
[ts-action]: https://www.npmjs.com/package/ts-action