Created
April 14, 2020 05:26
-
-
Save justinmoon/399f89cbcd3bcc98e8a1fe46462905be to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { readable } from "svelte/store"; | |
import { interpret } from "xstate"; | |
import { debugMachineTransition } from "./debug"; | |
export function useMachine(machine: any, options: any = {}) { | |
const service = interpret(machine, { ...options, devTools: true }); | |
const state = readable(machine.initialState, set => { | |
service | |
.onTransition(newState => { | |
debugMachineTransition(`${machine.id}`); | |
if (newState.changed) { | |
set(newState); | |
} | |
}) | |
.start(); | |
// Make sure the state is initialized in the store | |
set(service.state); | |
return () => { | |
service.stop(); | |
}; | |
}); | |
return { | |
state, | |
service, | |
send: service.send, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment