Created
January 19, 2020 00:17
-
-
Save darrenjennings/70b5c811016d9bfb163703439f920c4d to your computer and use it in GitHub Desktop.
vue useMachine.ts
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 { StateMachine, interpret, EventObject } from '@xstate/fsm' | |
import { ref, Ref, onBeforeMount } from '@vue/composition-api' | |
export default function useMachine<TContext, TEvent extends EventObject = EventObject> ( | |
stateMachine: StateMachine.Machine<TContext, TEvent, any>): { | |
current: Ref<StateMachine.State<TContext, TEvent, any>>, | |
send: StateMachine.Service<TContext, TEvent>['send'], | |
service: StateMachine.Service<TContext, TEvent>, | |
} { | |
const current = ref(stateMachine.initialState) as Ref<StateMachine.State<TContext, TEvent, any>> | |
const service = interpret(stateMachine).start() | |
onBeforeMount(() => { | |
service.subscribe(state => { | |
current.value = state | |
}) | |
}) | |
return { | |
current, | |
send: service.send, | |
service | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment