add createPayloadAction

This commit is contained in:
Yanick Champoux 2023-03-23 18:10:33 -04:00
parent bde9cac053
commit a9cb408521
3 changed files with 52 additions and 1 deletions

38
src/Updux.test.ts Normal file
View File

@ -0,0 +1,38 @@
import { test, expect } from 'vitest';
import Updux from './Updux';
test('subdux idempotency', () => {
// const c = new Updux({
// initial: 2,
// });
// const b = new Updux({
// subduxes: {
// c,
// },
// });
const foo = new Updux({
subduxes: {
a: new Updux({ initial: 2 }),
},
});
let fooState = foo.reducer(undefined, { type: 'noop' });
expect(foo.reducer(fooState, { type: 'noop' })).toBe(fooState);
return;
const store = foo.createStore();
const s1 = store.getState();
console.log(s1);
store.dispatch({ type: 'noop' });
const s2 = store.getState();
expect(s2.a).toBe(s1.a);
let bState = b.reducer(undefined, { type: 'noop' });
expect(b.reducer(bState, { type: 'noop' })).toBe(bState);
expect(s2.b).toBe(s1.b);
expect(s2).toBe(s1);
});

View File

@ -13,3 +13,16 @@ export const withPayload: WithPayload = ((prepare) =>
(...input) => ({ (...input) => ({
payload: prepare ? prepare(...input) : input[0], payload: prepare ? prepare(...input) : input[0],
})) as any; })) as any;
export const createPayloadAction = <
P extends any = any,
T extends string = string,
F extends (...args: any[]) => P = (input: P) => P,
>(
type: T,
prepare?: F,
) =>
createAction(
type,
withPayload<ReturnType<F>, Parameters<F>>(prepare ?? (id as any)),
);

View File

@ -1,5 +1,5 @@
import Updux from './Updux.js'; import Updux from './Updux.js';
export { withPayload, createAction } from './actions.js'; export { withPayload, createAction, createPayloadAction } from './actions.js';
export default Updux; export default Updux;