Files
smartstate/ts/smartstate.classes.stateaction.ts

29 lines
1022 B
TypeScript

import { StatePart } from './smartstate.classes.statepart.js';
/**
* Context object passed to action definitions, enabling safe nested dispatch.
* Use `context.dispatch()` to dispatch sub-actions inline (bypasses the mutation queue).
* Direct `statePart.dispatchAction()` from within an action will deadlock.
*/
export interface IActionContext<TStateType> {
dispatch<T>(action: StateAction<TStateType, T>, payload: T): Promise<TStateType>;
}
export interface IActionDef<TStateType, TActionPayloadType> {
(stateArg: StatePart<any, TStateType>, actionPayload: TActionPayloadType, context?: IActionContext<TStateType>): Promise<TStateType>;
}
/**
* an actionmodifier for the state
*/
export class StateAction<TStateType, TActionPayloadType> {
constructor(
public statePartRef: StatePart<any, any>,
public actionDef: IActionDef<TStateType, TActionPayloadType>
) {}
public trigger(payload: TActionPayloadType): Promise<TStateType> {
return this.statePartRef.dispatchAction(this, payload);
}
}