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
Here is an example of how to create a simple state machine using @deviltea/tiny-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"
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()