@deviltea/tiny-state-machine
v0.0.5
Published
[![npm version][npm-version-src]][npm-version-href] [![npm downloads][npm-downloads-src]][npm-downloads-href] [![bundle][bundle-src]][bundle-href] [![License][license-src]][license-href]
Readme
@deviltea/tiny-state-machine
Installation
To install the package, use either npm, yarn, or pnpm:
npm install @deviltea/tiny-state-machineyarn add @deviltea/tiny-state-machinepnpm add @deviltea/tiny-state-machineUsage
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()