The machine to hook-into.
The event to listen for.
Fire the callback when we transition to this state.
To hook-into onEvent, onEntering/ed, onExiting/ed, onSwitching/ed with side-effects cleanup, useStatebotEvent
:
import m from 'mithril'
import { withHooks } from 'mithril-hooks'
import { Statebot } from 'statebot'
import { useStatebot, useStatebotEvent } from 'statebot/hooks/mithril'
const bot = Statebot('loader', {
chart: `
idle ->
loading -> (loaded | failed) ->
idle
`
})
const { Enter, Emit, inState } = bot
const LoadingButton = withHooks(props => {
const state = useStatebot(bot)
useStatebotEvent(bot, 'onEntered', (toState) =>
if (toState !== 'loading') {
return
}
setTimeout(
bot.Emit(EVENT.LOAD_SUCCESS),
seconds(1)
)
)
// You can achieve the same with useEffect, and you
// get more control over the dependencies, too:
useEffect(() => {
const cleanupFn = bot.onExited('loading', () =>
setTimeout(
bot.Enter('idle'),
seconds(2)
)
)
return cleanupFn
}, [bot])
return (
<button
className={state}
onClick={Emit('start-loading')}
disabled={inState('loading')}
>
{inState('idle', 'Load')}
{inState('loading', 'Please wait...')}
{inState('loaded', 'Done!')} ({state})
</button>
)
})
function seconds(n) {
return n * 1000
}
The machine to hook-into.
The event to listen for.
Generated using TypeDoc
To hook-into onEvent, onEntering/ed, onExiting/ed, onSwitching/ed with side-effects cleanup,
useStatebotEvent
:Example