Skip to content

Instantly share code, notes, and snippets.

@AleksejDix
Last active November 18, 2021 10:47
Show Gist options
  • Save AleksejDix/22960857cba7220b429aeb1bc93bbf03 to your computer and use it in GitHub Desktop.
Save AleksejDix/22960857cba7220b429aeb1bc93bbf03 to your computer and use it in GitHub Desktop.
useActor.ts
import { shallowReactive, watchEffect } from '@vue/composition-api'
import { Interpreter, EventObject, Typestate, Actor, State } from 'xstate'
export function useActor<
TContext,
TEvent extends EventObject,
TTypestate extends Typestate<TContext> = { value: any; context: TContext }
>(
service:
| Actor<TContext, TEvent>
| Interpreter<TContext, any, TEvent, TTypestate>
) {
if (!service) {
throw new Error('useActor required an actor or an Interpreter as argument')
}
const actor = shallowReactive({
state: service.state as State<TContext, TEvent, any, TTypestate>,
send: service.send,
service,
})
watchEffect((onInvalidate) => {
// @ts-ignore
const { unsubscribe } = service.subscribe((currentState: any) => {
if (currentState.changed) {
actor.state = currentState
}
})
onInvalidate(unsubscribe)
})
return actor
}
----------------------------------------
how to use in VUe
setup(_props, context) {
const authActor = useActor<AuthMachineContext, AuthMachineEvents>(
context.root.$shop.state.context.authActor
)
return { authActor }
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment