createStore

This commit is contained in:
Yanick Champoux 2021-10-07 13:27:14 -04:00
parent 0ecb1059ee
commit b7ada06e3c
3 changed files with 37 additions and 4 deletions

View File

@ -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;
}
}

View File

@ -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 },
});

View File

@ -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;
};