effects in the updux

typescript
Yanick Champoux 2022-08-29 10:32:52 -04:00
parent 80a356ff1a
commit e3dce45f50
3 changed files with 28 additions and 8 deletions

View File

@ -38,7 +38,7 @@ test( "tutorial example", async () => {
store.dispatch.addTodo('Do the thing');
expect( store.getState() ).toMatchObject({
nextId:2, todos: [ 'Do the thing' ]
nextId:2, todos: [ { description: 'Do the thing', id: 1 } ]
})
});

View File

@ -1,9 +1,10 @@
import R from 'remeda';
import u from 'updeep';
import { createStore as reduxCreateStore } from 'redux';
import { createStore as reduxCreateStore, applyMiddleware } from 'redux';
import { buildSelectors } from './selectors.js';
import { buildUpreducer } from './upreducer.js';
import { buildMiddleware } from './middleware.js';
import { action, isActionGen } from './actions.js';
/**
@ -19,7 +20,7 @@ export class Updux {
#mutations = {};
#config = {};
#selectors = {};
#effects = {};
#effects = [];
constructor(config = {}) {
this.#config = config;
@ -42,6 +43,12 @@ export class Updux {
config.splatSelectors,
this.#subduxes,
);
if (Array.isArray(config.effects)) {
this.#effects = config.effects;
} else if (R.isObject(config.effects)) {
this.#effects = Object.entries(config.effects);
}
}
#addSubduxActions(_slice, subdux) {
@ -119,15 +126,24 @@ export class Updux {
return this.#mutations;
}
get middleware() {
return buildMiddleware(
this.#effects,
this.actions,
this.selectors,
this.subduxes,
);
}
createStore(initial = undefined, enhancerGenerator = undefined) {
// const enhancer = (enhancerGenerator ?? applyMiddleware)(
// this.middleware
// );
const enhancer = (enhancerGenerator ?? applyMiddleware)(
this.middleware,
);
const store = reduxCreateStore(
this.reducer,
initial ?? this.initial,
//enhancer
enhancer,
);
store.actions = this.actions;
@ -157,6 +173,10 @@ export class Updux {
return store;
}
addEffect(action, effect) {
this.#effects = [...this.#effects, [action, effect]];
}
}
export const dux = (config) => new Updux(config);

View File

@ -1,4 +1,4 @@
function isActionGen(action) {
export function isActionGen(action) {
return typeof action === 'function' && action.type;
}