Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created January 6, 2022 04:38
Show Gist options
  • Save jtmthf/691399e03dbf0c58fa720deb6edb5bc7 to your computer and use it in GitHub Desktop.
Save jtmthf/691399e03dbf0c58fa720deb6edb5bc7 to your computer and use it in GitHub Desktop.
import { useLayoutEffect, useState } from 'react';
import { EventObject, MachineOptions, StateMachine, Typestate } from 'xstate';
type MaybeLazy<T> = T | (() => T);
export function useMachineOptions<
TContext,
TEvent extends EventObject,
TTypestate extends Typestate<TContext> = { value: any; context: TContext }
>(
getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>,
options: Partial<MachineOptions<TContext, TEvent>> = {},
): StateMachine<TContext, any, TEvent, TTypestate> {
const [machine] = useState(getMachine);
const {
guards,
actions,
activities,
services,
delays,
} = options;
const [machineWithConfig] = useState(() => {
const machineConfig = {
guards,
actions,
activities,
services,
delays
};
return machine.withConfig(machineConfig);
});
useLayoutEffect(() => {
Object.assign(machine.options.actions, actions);
Object.assign(machine.options.guards, guards);
Object.assign(machine.options.activities, activities);
Object.assign(machine.options.services, services);
Object.assign(machine.options.delays, delays);
}, [actions, guards, activities, services, delays]);
return machineWithConfig;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment