@supunlakmal/hooks
Version:
A collection of reusable React hooks
39 lines (38 loc) • 1.75 kB
TypeScript
export interface StateMachineConfig<TState extends string, TEvent extends string, TContext = any> {
initial: TState;
context?: TContext;
states: {
[State in TState]: {
on?: {
[Event in TEvent]?: {
target: TState;
actions?: Array<(context: TContext, eventPayload?: any) => Partial<TContext> | void>;
cond?: (context: TContext, eventPayload?: any) => boolean;
} | TState;
};
entry?: Array<(context: TContext) => Partial<TContext> | void>;
exit?: Array<(context: TContext) => Partial<TContext> | void>;
};
};
}
export interface StateMachineInstance<TState extends string, TEvent extends string, TContext = any> {
/** The current state value (e.g., 'idle', 'loading', 'success'). */
currentState: TState;
/** The current context data associated with the state machine. */
context: TContext;
/** Function to send an event to the state machine to trigger transitions. */
send: (event: TEvent | {
type: TEvent;
payload?: any;
}) => void;
/** Function to check if the current state matches a given state value. */
matches: (state: TState) => boolean;
}
/**
* Manages complex state using an explicit finite state machine definition.
* Inspired by libraries like XState.
*
* @param config The state machine configuration object.
* @returns An object containing the current state, context, and a send function.
*/
export declare const useFiniteStateMachine: <TState extends string, TEvent extends string, TContext = any>(config: StateMachineConfig<TState, TEvent, TContext>) => StateMachineInstance<TState, TEvent, TContext>;