diff --git a/src/Updux.js b/src/Updux.js index f46a1cc..eeaa6e8 100644 --- a/src/Updux.js +++ b/src/Updux.js @@ -1,5 +1,7 @@ import moize from 'moize'; import u from '@yanick/updeep'; +import { createStore as reduxCreateStore } from 'redux'; +import { mapValues } from 'lodash-es'; import { buildInitial } from './buildInitial/index.js'; import { buildActions } from './buildActions/index.js'; @@ -74,13 +76,16 @@ export class Updux { addAction(type, payloadFunc) { const theAction = action(type, payloadFunc); - this.#actions = u({ [type]: theAction }, this.#actions); + this.#actions = { ...this.#actions, [type]: theAction }; return theAction; } addSelector(name, func) { - this.#selectors[name] = func; + this.#selectors = { + ...this.#selectors, + [name]: func, + }; return func; } @@ -94,4 +99,28 @@ export class Updux { return this; } + + createStore() { + const store = reduxCreateStore(this.reducer); + + store.actions = this.actions; + + store.selectors = mapValues(this.selectors, (selector) => { + return (...args) => { + let result = selector(store.getState()); + + if (typeof result === 'function') return result(...args); + + return result; + }; + }); + + for (const action in this.actions) { + store.dispatch[action] = (...args) => { + return store.dispatch(this.actions[action](...args)); + }; + } + + return store; + } } diff --git a/src/Updux.test.js b/src/Updux.test.js index 0d371ef..da09330 100644 --- a/src/Updux.test.js +++ b/src/Updux.test.js @@ -95,7 +95,7 @@ test('basic selectors', { todo: true }, async (t) => { t.equal(store.selectors.getAdd(7), 8); }); -test('mutations', { todo: true }, async () => { +test('mutations', { todo: false }, async (t) => { const alpha = new Updux({ initial: { quux: 3 }, }); diff --git a/src/actions.js b/src/actions.js index dd6b6a6..ab7b7c7 100644 --- a/src/actions.js +++ b/src/actions.js @@ -2,7 +2,11 @@ export function action(type, payloadFunction = null) { const generator = function (payloadArg) { const result = { type }; - if (payloadFunction) result.payload = payloadFunction(payloadArg); + if (payloadFunction) { + result.payload = payloadFunction(payloadArg); + } else { + if (payloadArg !== undefined) result.payload = payloadArg; + } return result; };