diff --git a/docs/tutorial-reactions.test.js b/docs/tutorial-reactions.test.js new file mode 100644 index 0000000..d32f924 --- /dev/null +++ b/docs/tutorial-reactions.test.js @@ -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); +}); + diff --git a/docs/tutorial.md b/docs/tutorial.md index 6626941..e3d48e6 100644 --- a/docs/tutorial.md +++ b/docs/tutorial.md @@ -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