createStore
This commit is contained in:
parent
0ecb1059ee
commit
b7ada06e3c
33
src/Updux.js
33
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;
|
||||
}
|
||||
}
|
||||
|
@ -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 },
|
||||
});
|
||||
|
@ -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;
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user