Function useStatebot

  • 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

     import m from 'mithril'
    import { withHooks as MithrilComponent } from 'mithril-hooks'

    import { Statebot } from 'statebot'
    import { useStatebot } from 'statebot/hooks/mithril'

    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 } = loadMachine

    let LoadingButton = MithrilComponent(() => {
    let state = useStatebot(loadMachine)

    return m(
    'button',
    {
    className: state,
    onclick: Emit('start-loading'),
    disabled: !inState('idle')
    },
    inState('idle', 'Load'),
    inState('waiting', 'Please wait...'),
    inState('loaded', 'Done!'),
    inState('failed', 'Whoops!')
    )
    })

    let ResetButton = MithrilComponent(() => {
    return m(
    'button',
    {
    onclick: Enter('idle')
    },
    'Reset'
    )
    })

    Returns

    The current state of the machine.

    Parameters

    Returns string

Generated using TypeDoc