From a9cb4085214bbf6b1eb7ee5820cb580e875178ae Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Thu, 23 Mar 2023 18:10:33 -0400 Subject: [PATCH] add createPayloadAction --- src/Updux.test.ts | 38 ++++++++++++++++++++++++++++++++++++++ src/actions.ts | 13 +++++++++++++ src/index.ts | 2 +- 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/Updux.test.ts diff --git a/src/Updux.test.ts b/src/Updux.test.ts new file mode 100644 index 0000000..822aaa2 --- /dev/null +++ b/src/Updux.test.ts @@ -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); +}); diff --git a/src/actions.ts b/src/actions.ts index f8d7dcf..cf559b6 100644 --- a/src/actions.ts +++ b/src/actions.ts @@ -13,3 +13,16 @@ export const withPayload: WithPayload = ((prepare) => (...input) => ({ payload: prepare ? prepare(...input) : input[0], })) 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, Parameters>(prepare ?? (id as any)), + ); diff --git a/src/index.ts b/src/index.ts index 6488bac..6e14d5a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ import Updux from './Updux.js'; -export { withPayload, createAction } from './actions.js'; +export { withPayload, createAction, createPayloadAction } from './actions.js'; export default Updux;