63 lines
1.4 KiB
Markdown
63 lines
1.4 KiB
Markdown
|
# Tutorial
|
||
|
|
||
|
This tutorial walks you through the features of `Updux` using the
|
||
|
time-honored example of the implementation of Todo list store.
|
||
|
|
||
|
We'll be using
|
||
|
[updeep](https://www.npmjs.com/package/updeep) to
|
||
|
help with immutability and deep merging,
|
||
|
but that's totally optional. If `updeep` is not your bag,
|
||
|
it can easily be substitued with, say, [immer][], [lodash][], or even
|
||
|
plain JavaScript.
|
||
|
|
||
|
## Definition of the state
|
||
|
|
||
|
To begin with, let's define that has nothing but an initial state.
|
||
|
|
||
|
```js
|
||
|
import { Updux } from 'updux';
|
||
|
|
||
|
const todosDux = new Updux({
|
||
|
initial: {
|
||
|
next_id: 1,
|
||
|
todos: [],
|
||
|
}
|
||
|
});
|
||
|
```
|
||
|
|
||
|
Congrats! You have written your first Updux object. It
|
||
|
doesn't do a lot, but you can already create a store out of it, and its
|
||
|
initial state will be automatically set:
|
||
|
|
||
|
```js
|
||
|
const store = todosDux.createStore();
|
||
|
|
||
|
console.log(store.getState()); // prints { next_id: 1, todos: [] }
|
||
|
```
|
||
|
|
||
|
## Add actions
|
||
|
|
||
|
This is all good, but a little static. Let's add actions!
|
||
|
|
||
|
```js
|
||
|
const todosDux = new Updux({
|
||
|
initial: {
|
||
|
next_id: 1,
|
||
|
todos: [],
|
||
|
},
|
||
|
{
|
||
|
addTodo: null,
|
||
|
todoDone: null,
|
||
|
}
|
||
|
});
|
||
|
```
|
||
|
|
||
|
### Accessing actions
|
||
|
|
||
|
Once an action is defined, its creator is accessible via the `actions` accessor.
|
||
|
|
||
|
```js
|
||
|
console.log( todosDux.actions.addTodo('write tutorial') );
|
||
|
// prints { type: 'addTodo', payload: 'write tutorial' }
|
||
|
```
|