How to use the xstate.interpret function in xstate

To help you get started, we’ve selected a few xstate examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github coodoo / xstate-examples / crud-v1-services / src / utils / useMyHooks.js View on Github external
export const useMachineEx = (machine, { debug=false, name='', interpreterOptions={}}) => {
	// eslint-disable-next-line
	const [_, force] = useState(0)
	const machineRef = useRef(null)
	const serviceRef = useRef() // started Interpreter

	if(machineRef.current !== machine){

		machineRef.current = machine

		serviceRef.current = interpret(machineRef.current, interpreterOptions)
		.onTransition( state => {

			if(state.event.type === 'xstate.init') {
				// debugger	//
				return
			}
			//
			if( state.changed === false && debug === true ){
				console.error(
					`\n\n💣💣💣 [UNHANDLED EVENT][useMachine]💣💣💣\nEvent=`,
					state.event,

					'\nState=',
					state.value, state,

					'\nContext=',
github coodoo / xstate-examples / _old / fsm-service-1-callback / src / useMachine.js View on Github external
() =>

    	// 啟動 fsm 的必要過程
      interpret(machine, { execute: false })
      	// 這支主要目地是為了打印當前狀態,順便操作 internal state 指令 setCurrent
        .onTransition(state => {
          options.log && console.log("CONTEXT:", state.context);
          setCurrent(state);
        })
        .onEvent(e => options.log && console.log("EVENT:", e)),
    []
github reach / reach-ui / packages / adapter / src / index.js View on Github external
function useMachineService(chart, refs, debug = true) {
  const [state, setState] = useState(chart.initialState);

  const serviceRef = useRef(null);
  if (serviceRef.current === null) {
    serviceRef.current = interpret(chart).start();
  }

  // add refs to every event so we can use them to perform actions previous
  // strategy was send an "update" event to the machine whenever we rendered in
  // React, but that got a little unweildy (had to add UPDATE events to every
  // state, caused lots of noise in the service subscription), this seems
  // better.
  const send = rawEvent => {
    const event = typeof rawEvent === "string" ? { type: rawEvent } : rawEvent;
    if (event.refs) throw new Error("refs is a reserved event key");
    const unwrapped = Object.keys(refs).reduce((unwrapped, name) => {
      unwrapped[name] = refs[name].current;
      return unwrapped;
    }, {});
    serviceRef.current.send({ ...event, refs: unwrapped });
  };
github coodoo / xstate-examples / crud-v1-services / src / utils / useMachine-最新版.js View on Github external
// Create the machine only once
  // See https://reactjs.org/docs/hooks-faq.html#how-to-create-expensive-objects-lazily
  if (machineRef.current === null) {
    machineRef.current = machine.withConfig(machineConfig, {
      ...machine.context,
      ...context
    } as TContext);
  }

  // Reference the service
  const serviceRef = useRef | null>(null);

  // Create the service only once
  if (serviceRef.current === null) {
    serviceRef.current = interpret(
      machineRef.current,
      interpreterOptions
    ).onTransition(state => {
      // Update the current machine state when a transition occurs
      if (state.changed) {
        setCurrent(state);
      }
    });
  }

  const service = serviceRef.current;

  // Make sure actions are kept updated when they change.
  // This mutation assignment is safe because the service instance is only used
  // in one place -- this hook's caller.
  useEffect(() => {
github kyleshevlin / intro-to-state-machines-and-xstate-course / lessons / using-interpret-on-a-machine / after.js View on Github external
on: {
        BREAK: 'broken',
        TOGGLE: 'unlit',
      },
    },
    unlit: {
      on: {
        BREAK: 'broken',
        TOGGLE: 'lit',
      },
    },
    broken: { type: 'final' },
  },
})

const service = interpret(lightBulbMachine).start()

service.onTransition(state => {
  console.log(state.value)
})

service.send('TOGGLE')
service.send('BREAK')
github doczjs / docz / core / docz-core / src / bundler / server.ts View on Github external
export const server = (args: Args) => async () => {
  const doczrcFilepath = await findUp(finds('docz'))
  const machine = devServerMachine.withContext({ args, doczrcFilepath })
  const service = interpret(machine).onTransition(state => {
    if (args.debug) {
      console.log(state.value)
    }
  })

  return {
    start: async () => {
      service.start()
      service.send('START_MACHINE')
      process.on('exit', () => {
        service.stop()
      })
    },
  }
}
github DevanB / xstate-examples / trivia-game-vue / src / App.vue View on Github external
data() {
    return {
      machineService: interpret(machine),
      current: machine.initialState
    };
  },
  methods: {
github ablehq / firestore-explorer / firebase-proxy / dist / parser / FirebaseReadQueryParser.js View on Github external
exports.parse = (code) => {
    try {
        let fsm = xstate_1.interpret(_1.fsmGenerator()).start();
        const ast = acorn_1.Parser.parse(code);
        let currentNode = null;
        walk.simple(ast, {
            Identifier(node) {
                currentNode = node;
                try {
                    fsm.send({
                        type: node.name,
                        node: node
                    });
                }
                catch (error) { }
            },
            CallExpression(node) {
                currentNode = node;
                let property = currentNode.callee.property;
github stefanoslig / angular-xstate / src / app / auth / +xstate / auth-machine.service.ts View on Github external
},
    guards: {
      isLoggedOut: () => !localStorage.getItem('jwtToken')
    },
    actions: {
      assignUser: assign({
        user: (context, event) => event.user
      }),
      assignErrors: assign({
        errors: (context, event) => event.error.error.errors
      })
    }
  };

  private _authMachine = Machine(authMachineConfig, this.authMachineOptions);
  public authMachine = interpret(this._authMachine, { devTools: true }).start();

  public authState$: Observable> = fromEventPattern(
    (handler: StateListener) => this.authMachine.onTransition(handler)
  ).pipe(
    startWith([this.authMachine.initialState, {}] as any),
    map(([state, _]) => state)
  );

  constructor(private authService: AuthService, private router: Router) {}
}