From e3dce45f507f3a427eb4c5223739b77a5f8e3bc5 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Mon, 29 Aug 2022 10:32:52 -0400 Subject: [PATCH] effects in the updux --- docs/tutorial-effects.test.js | 2 +- src/Updux.js | 32 ++++++++++++++++++++++++++------ src/actions.js | 2 +- 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/docs/tutorial-effects.test.js b/docs/tutorial-effects.test.js index 4f361a4..de404e8 100644 --- a/docs/tutorial-effects.test.js +++ b/docs/tutorial-effects.test.js @@ -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 } ] }) }); diff --git a/src/Updux.js b/src/Updux.js index d17041b..7577f38 100644 --- a/src/Updux.js +++ b/src/Updux.js @@ -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); diff --git a/src/actions.js b/src/actions.js index db1f965..51ad508 100644 --- a/src/actions.js +++ b/src/actions.js @@ -1,4 +1,4 @@ -function isActionGen(action) { +export function isActionGen(action) { return typeof action === 'function' && action.type; }