How to use xstate - 10 common examples

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 LevelbossMike / ember-statecharts / tests / dummy / app / components / viz / statechart-viz / component.js View on Github external
interpretMachine(machine) {
    // parse machine actions // get actions from them and stub them out
    const actionNames = Object.keys(machine.options.actions || {});

    const stubbedActions = actionNames.reduce((acc, name) => { 
      acc[name] = this.onActionTriggered.bind(this, name);
      return acc;
    }, {})

    const interpreter = interpret(this.machine.withConfig({
      actions: stubbedActions
    })).onTransition(nextState => {
      this.set('currentState', nextState);
    })

    return interpreter.start();
  },
github ArkEcosystem / core / packages / core-test-utils / lib / matchers / blockchain / transition.js View on Github external
const toTransition = (machine, transition) => {
  const state = machine.transition(transition.from, transition.on)

  return {
    // FIXME isNot is necessary to write the right message
    // @see https://facebook.github.io/jest/docs/en/expect.html#expectextendmatchers
    message: () => `Expected machine to ${this.isNot ? 'not' : ''} transition to "${transition.to}" from "${transition.from}" on "${transition.on}"`,
    pass: matchesState(transition.to, state.value)
  }
}
github coodoo / xstate-examples / crud-v1-services / src / fsm / actions.js View on Github external
console.log('[MODAL_DELETE_ITEM_RESULT]', e)
	const { result } = e
	ctx.notify(result.info)
})

export const modalErrorDataClose = assign((ctx, e) => {
	ctx.modalData = null
	ctx.notify('Loading Error dismissed')
})

export const modalErrorDataRetry = assign((ctx, e) => {
	ctx.modalData = null
	ctx.notify('Loading Error dismissed')
})

export const createNewItem = assign((ctx, e) => {
	// config which screen to exit to from creating new item screen
	ctx.exitNewItemTo = e.exitTo
})

// optimistic update, insert the item with local id
export const preSubmitNewItem = assign((ctx, e) => {
	const newItem = e.payload
	ctx.items.push(newItem)
	ctx.selectedItemId = newItem.id
})

// then invoke service to persist new item via external api call
export const submitNewItem = send(
	(ctx, e) => ({
		type: 'ServiceCreateItems',
		payload: e.payload,
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 coodoo / xstate-examples / _old / fsm-service-3-actor / src / fsm / workerActions.js View on Github external
import { assign } from '../xstate-custom/xstateImmer'
import { send, sendParent } from 'xstate'
import { CompServiceTypes } from './compressionService'
import { MainTypes } from './mainMachine'

export const onEntry = assign((ctx, e) => {
	// console.log('[WorkerMachine ctx]', ctx.name)
})

export const startJobAssign = assign((ctx, e) => {
	// console.log('[SubMachine startJob]', e)
})

export const startJobSend = send(
	(ctx, e) => ({
		type: CompServiceTypes.compressSong,
		data: ctx,
	}),
	{ to: 'CompressionService' },
)


export const workerProgressAssign = assign((ctx, e) => {
	const { progress } = e.job
	// console.log( `workerMachine ${id}: ${progress}` )
	ctx.progress = progress
	return ctx
})

export const workerDoneAssign = assign((ctx, e) => {
github coodoo / xstate-examples / crud-v1-services / src / fsm / actions.js View on Github external
})

export const createNewItem = assign((ctx, e) => {
	// config which screen to exit to from creating new item screen
	ctx.exitNewItemTo = e.exitTo
})

// optimistic update, insert the item with local id
export const preSubmitNewItem = assign((ctx, e) => {
	const newItem = e.payload
	ctx.items.push(newItem)
	ctx.selectedItemId = newItem.id
})

// then invoke service to persist new item via external api call
export const submitNewItem = send(
	(ctx, e) => ({
		type: 'ServiceCreateItems',
		payload: e.payload,
		forceFail: e.forceFail,
	}),
	{ to: 'ItemService' },
)

// after data was persisted to server, replace local item id with the official one sent back from the server
export const newItemSuccess = assign((ctx, e) => {
	const {
		result: { info, serverItem, localItem },
	} = e
	// console.log( '[NEW_ITEM_SUCCESS]', serverItem )

	ctx.items = ctx.items.map(it => (it.id === localItem.id ? serverItem : it))
github coodoo / xstate-examples / _old / fsm-service-3-actor / src / fsm / workerActions.js View on Github external
// console.log( '\t[workerDone]', ctx, e )
	const { progress } = e.job
	ctx.progress = progress
	return ctx
})

export const workerDoneSend = sendParent((ctx, e) => ({
	type: MainTypes.updateJob,
	song: ctx,
}))

export const pauseFileAssign = assign((ctx, e) => {
	// console.log('\t[pauseFile]', e.id)
})

export const pauseFileSend = send(
	(ctx, e) => ({
		type: CompServiceTypes.pauseSong,
		data: ctx.id,
	}),
	{ to: 'CompressionService' },
)

export const resumeFileSend = send(
	(ctx, e) => ({
		type: CompServiceTypes.resumeSong,
		data: { id: ctx.id, progress: ctx.progress },
	}),
	{ to: 'CompressionService' },
)

export const cancelFileSend = send(
github coodoo / xstate-examples / _old / fsm-service-3-actor / src / fsm / workerActions.js View on Github external
song: ctx,
}))

export const pauseFileAssign = assign((ctx, e) => {
	// console.log('\t[pauseFile]', e.id)
})

export const pauseFileSend = send(
	(ctx, e) => ({
		type: CompServiceTypes.pauseSong,
		data: ctx.id,
	}),
	{ to: 'CompressionService' },
)

export const resumeFileSend = send(
	(ctx, e) => ({
		type: CompServiceTypes.resumeSong,
		data: { id: ctx.id, progress: ctx.progress },
	}),
	{ to: 'CompressionService' },
)

export const cancelFileSend = send(
	(ctx, e) => ({
		type: CompServiceTypes.cancelSong,
		data: ctx.id,
	}),
	{ to: 'CompressionService' },
)

export const cancelFileSendParent = sendParent((ctx, e) => ({
github coodoo / xstate-examples / crud-v1-services / src / fsm / actions.js View on Github external
import { send, assign } from 'xstate'

export const reloadItems = send(
	{ type: 'ServiceLoadItems' }, // the event to be sent
	{ to: 'ItemService' }, // the target servcie to receive that event
)

export const listDataSuccess = assign((ctx, evt) => {
	ctx.items = evt.data
	ctx.notify('Data fetched 1')
	ctx.notify('Data fetched 2')
	ctx.notify('Data fetched 3')
})

export const listDataError = assign((ctx, e) => {
	console.log('\n[listDataError]', e.data)
	//
	ctx.modalData = {
		type: 'MODAL_ERROR',