For hooking-into Statebots that have life-cycles independent of the components that use them, useStatebot:
useStatebot
You can play around with this one in a CodeSandbox.
import React from 'react'import { Statebot } from 'statebot'import { useStatebot } from 'statebot/hooks/react'export let loadMachine = Statebot('loader', { chart: ` idle -> waiting -> loaded | failed -> idle `})loadMachine.performTransitions(({ emit }) => ({ 'idle -> waiting': { on: 'start-loading', then: () => { // Fail half the time for this demo let fail = Math.random() > 0.5 setTimeout(() => { fail ? emit('error') : emit('success') }, 1000) } }, 'waiting -> loaded': { on: 'success' }, 'waiting -> failed': { on: 'error' }}))let { Enter, Emit, inState } = loadMachinefunction LoadingButton() { let state = useStatebot(loadMachine) return ( <button className={state} onClick={Emit('start-loading')} disabled={!inState('idle')} > {inState('idle', 'Load')} {inState('waiting', 'Please wait...')} {inState('loaded', 'Done!')} {inState('failed', 'Whoops!')} </button> )}function ResetButton() { return <button onClick={Enter('idle')}>Reset</button>}
The current state of the machine.
The machine to hook-into.
Generated using TypeDoc
For hooking-into Statebots that have life-cycles independent of the components that use them,
useStatebot
:You can play around with this one in a CodeSandbox.
Example
Returns
The current state of the machine.