can add actions via addEffect

This commit is contained in:
Yanick Champoux 2024-08-13 11:49:11 -04:00
parent ae79a08662
commit 98da41c07e
3 changed files with 33 additions and 2 deletions

View File

@ -270,7 +270,9 @@ export default class Updux<D extends DuxConfig> {
addEffect<AC extends rtk.ActionCreatorWithPreparedPayload<any, any, string, never, never>>(
actionCreator: AC,
effect: EffectMiddleware<D, ReturnType<AC>>,
): Updux<D>;
): Updux<D & {
actions: Record<AC extends { type: infer T } ? T : never, AC>
}>;
addEffect(
guardFunc: (action: AnyAction) => boolean,
effect: EffectMiddleware<D>,
@ -292,6 +294,9 @@ export default class Updux<D extends DuxConfig> {
}
}
if (!this.actions[actionCreator.type])
this.addAction(actionCreator);
const test = actionCreator.hasOwnProperty('match')
? actionCreator.match
: actionCreator;

View File

@ -2,7 +2,7 @@ import { test, expect } from 'vitest';
import Updux from './Updux.js';
import { buildEffectsMiddleware } from './effects.js';
import { createAction, withPayload } from './index.js';
import { AnyAction, Dispatch } from '@reduxjs/toolkit';
import { ActionCreator, AnyAction, Dispatch } from '@reduxjs/toolkit';
import { AugmentedMiddlewareAPI } from './types.js';
test('addEffect signatures', () => {
@ -221,5 +221,19 @@ test('catchall addEffect', () => {
expect(spy).toHaveBeenCalled();
});
test('addEffect with unknown actionCreator adds it', () => {
const foo = createAction('foo');
const dux = new Updux({}).addEffect(
foo, () => () => () => { }
);
expectTypeOf(dux.actions.foo).toMatchTypeOf<
ActionCreator<any>
>();
expect(dux.actions.foo()).toMatchObject({ type: 'foo' });
});
// TODO subdux effects
// TODO allow to subscribe / unsubscribe effects?

View File

@ -1,5 +1,6 @@
import { createAction } from '@reduxjs/toolkit';
import { test, expect } from 'vitest';
import { withPayload } from './actions.js';
import Updux from './Updux.js';
test('set a mutation', () => {
@ -110,3 +111,14 @@ test('setDefaultMutation return value', () => {
expectTypeOf(withDM.initialState).toBeNumber();
});
test('addMutation with createAction', () => {
const setName = createAction('setName', withPayload<string>());
const dux = new Updux({
initialState: {
name: '',
round: 1,
},
}).addMutation(setName, (name) => (state) => ({ ...state, name }));
});