Last active
November 18, 2021 10:47
-
-
Save AleksejDix/22960857cba7220b429aeb1bc93bbf03 to your computer and use it in GitHub Desktop.
useActor.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 { 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