Function useStatebotEvent

  • To hook-into onEvent, onEntering/ed, onExiting/ed, onSwitching/ed with side-effects cleanup, useStatebotEvent:

    Example

    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', 'loading', () =>
    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
    }

    Parameters

    • bot: TStatebotFsm

      The machine to hook-into.

    • eventName: TEventName

      The event to listen for.

    • state: string

      Fire the callback when we transition to this state.

    • cb: Function

    Returns any

  • To hook-into onEvent, onEntering/ed, onExiting/ed, onSwitching/ed with side-effects cleanup, useStatebotEvent:

    Example

    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
    }

    Parameters

    Returns any

Generated using TypeDoc