Skip to content

Commit

Permalink
feat: Update code
Browse files Browse the repository at this point in the history
  • Loading branch information
nuintun committed Jun 11, 2024
1 parent b40a265 commit ffe5345
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions app/js/hooks/useStateMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,11 @@ export interface StateOptions<C, S extends string, E extends string> {
on?: {
[key in E]?: Transition<C, S, E>;
};
effect?: (send: Send<E>, update: Update<C>) => void | (() => void);
effect?: (send: Send<E>, update: Update<C>) => Destructor;
}

type Destructor = void | (() => void) | Promise<void | (() => void)>;

type Action<C, E extends string> = UpdateAction<C> | TransitionAction<E>;

type Transition<C, S extends string, E extends string> = S | { target: S; guard?: Guard<C, S, E> };
Expand Down Expand Up @@ -216,7 +218,29 @@ export default function useStateMachine<C = undefined, S extends string = string
}, []);

// We are bypassing the linter here because we deliberately want the effects to run on explicit machine state changes.
useEffect(() => options.states[state.value].effect?.(send, update), [state.value]);
useEffect(() => {
const returned = (async () => {
const { effect } = options.states[state.value];

try {
return await effect?.(send, update);
} catch (error) {
console.error(error);
}
})();

return () => {
returned.then(exit => {
if (isFunction(exit)) {
try {
exit();
} catch (error) {
console.error(error);
}
}
});
};
}, [state.value]);

return [state, send, update];
}

0 comments on commit ffe5345

Please sign in to comment.