updux/dist/tutorial/effects.test.js

35 lines
1.2 KiB
JavaScript

import { test, expect } from 'vitest';
/// --8<-- [start:effects-1]
import u from '@yanick/updeep-remeda';
import * as R from 'remeda';
import Updux, { createAction, withPayload } from 'updux';
const addTodoWithId = createAction('addTodoWithId', withPayload());
const incNextId = createAction('incNextId');
const addTodo = createAction('addTodo', withPayload());
const todosDux = new Updux({
initialState: { nextId: 1, todos: [] },
actions: { addTodo, incNextId, addTodoWithId },
selectors: {
nextId: ({ nextId }) => nextId,
},
});
todosDux.addMutation(addTodoWithId, (todo) => u({
todos: R.concat([u(todo, { done: false })]),
}));
todosDux.addMutation(incNextId, () => u({ nextId: (id) => id + 1 }));
todosDux.addEffect('addTodo', ({ getState, dispatch }) => (next) => (action) => {
const id = getState.nextId();
dispatch.incNextId();
next(action);
dispatch.addTodoWithId({ id, description: action.payload });
});
const store = todosDux.createStore();
store.dispatch.addTodo('write tutorial');
/// --8<-- [end:effects-1]
test('basic', () => {
expect(store.getState()).toMatchObject({
nextId: 2,
todos: [{ id: 1, description: 'write tutorial', done: false }],
});
});