Skip to content

Instantly share code, notes, and snippets.

@darrenjennings
Created January 19, 2020 00:17
Show Gist options
  • Save darrenjennings/70b5c811016d9bfb163703439f920c4d to your computer and use it in GitHub Desktop.
Save darrenjennings/70b5c811016d9bfb163703439f920c4d to your computer and use it in GitHub Desktop.
vue useMachine.ts
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