Skip to content

Instantly share code, notes, and snippets.

@justinmoon
Created April 14, 2020 05:26
Show Gist options
  • Save justinmoon/399f89cbcd3bcc98e8a1fe46462905be to your computer and use it in GitHub Desktop.
Save justinmoon/399f89cbcd3bcc98e8a1fe46462905be to your computer and use it in GitHub Desktop.
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