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

    function 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>
    }

    Returns

    The current state of the machine.

    Parameters

    Returns any

Generated using TypeDoc