116 lines
2.5 KiB
Markdown
116 lines
2.5 KiB
Markdown
```
|
|
|
|
```
|
|
|
|
--8<- "docs/tutorial-effects.test.ts:effects-1"
|
|
|
|
```
|
|
|
|
|
|
```
|
|
|
|
## Subduxes
|
|
|
|
Now that we have all the building blocks, we can embark on the last and
|
|
funkiest part of Updux: its recursive nature.
|
|
|
|
### Recap: the Todos dux, undivided
|
|
|
|
Upduxes can be divided into sub-upduxes that deal with the various parts of
|
|
the global state. This is better understood by working out an example, so
|
|
let's recap on the Todos dux we have so far:
|
|
|
|
```title="todos-monolith.ts"
|
|
--8<- "docs/tutorial-monolith.test.ts:mono"
|
|
```
|
|
|
|
This store has two main components: the `nextId`, and the `todos` collection.
|
|
The `todos` collection is itself composed of the individual `todo`s. Let's
|
|
create upduxes for each of those.
|
|
|
|
### NextId dux
|
|
|
|
```js title="nextId.ts"
|
|
--8<- "docs/nextId.ts:dux"
|
|
```
|
|
|
|
### Todo updux
|
|
|
|
```title="todo.ts"
|
|
--8<- "docs/todo.ts"
|
|
```
|
|
|
|
### Todos updux
|
|
|
|
```title="todos.ts"
|
|
--8<- "docs/todos.ts"
|
|
```
|
|
|
|
### Main store
|
|
|
|
```title="todoList.ts"
|
|
--8<- "docs/todoList.ts"
|
|
```
|
|
|
|
Tadah! We had to define the `addTodo` effect at the top level as it needs to
|
|
access the `getNextId` selector from `nextId` and the `addTodoWithId`
|
|
action from the `todos`.
|
|
|
|
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,
|
|
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 })
|
|
}
|
|
});
|
|
```
|
|
|
|
[immer]: https://www.npmjs.com/package/immer
|
|
[lodash]: https://www.npmjs.com/package/lodash
|
|
[ts-action]: https://www.npmjs.com/package/ts-action
|
|
[remeda]: remedajs.com/
|