Skip to content

Latest commit

 

History

History

core

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

@deviltea/tiny-state-machine

npm version npm downloads bundle License

Installation

To install the package, use either npm, yarn, or pnpm:

npm install @deviltea/tiny-state-machine
yarn add @deviltea/tiny-state-machine
pnpm add @deviltea/tiny-state-machine

Usage

Here is an example of how to create a simple state machine using @deviltea/tiny-state-machine.

Example: Basic State Machine

import { createMachine } from '@deviltea/tiny-state-machine'

// Define a simple state machine with three states: idle, loading, and finished
const machine = createMachine({
	initial: 'idle',
	states: {
		idle: {
			on: {
				start: 'loading',
			},
		},
		loading: {
			on: {
				done: 'finished',
			},
		},
		finished: {},
	},
})

console.log(machine.currentState) // "idle"

// Transition to the next state
machine.send('start')
console.log(machine.currentState) // "loading"

// Finish the transition
machine.send('done')
console.log(machine.currentState) // "finished"

Example: Adding Transition Handlers

You can also add handlers that will be called during state transitions.

import { createMachine } from '@deviltea/tiny-state-machine'

const machine = createMachine({
	initial: 'idle',
	states: {
		idle: {
			on: {
				start: 'loading',
			},
		},
		loading: {
			on: {
				done: 'finished',
			},
		},
		finished: {},
	},
})

const unsubscribe = machine.onTransition(({ transition }) => {
	console.log(
		`Transitioned from ${transition.source} to ${transition.target} via event '${transition.event}'`
	)
})

machine.send('start') // Logs: Transitioned from idle to loading via event 'start'
machine.send('done') // Logs: Transitioned from loading to finished via event 'done'

unsubscribe()

License

MIT License © 2023-PRESENT DevilTea