Created
January 6, 2022 04:38
-
-
Save jtmthf/691399e03dbf0c58fa720deb6edb5bc7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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