statebot
    Preparing search index...

    Function useStatebotFactory

    • For Statebots whose life-cycles are tied to the components using them, useStatebotFactory:

      Parameters

      • name: string

        The name of the machine.

      • config: TStatebotOptions & { onTransitions?: any; performTransitions?: any }

        The chart and other configuration.

      Returns { bot: TStatebotFsm; state: string }

      The current state of the machine and the machine itself.

      import React from 'react'

      import { useStatebotFactory } from 'statebot/hooks/react'

      let CHART = `
      idle ->
      loading -> (loaded | failed) ->
      idle
      `

      let EVENT = {
      START_LOADING: 'start-loading',
      LOAD_SUCCESS: 'load-success',
      LOAD_ERROR: 'load-error'
      }

      function LoadingButton (props) {
      let { state, bot } = useStatebotFactory(
      'loading-button',
      {
      chart: CHART,
      startIn: 'idle',
      logLevel: 4,

      performTransitions: ({ Emit }) => ({
      'idle -> loading': {
      on: EVENT.START_LOADING,
      then: () => setTimeout(
      Emit(EVENT.LOAD_SUCCESS),
      1000
      )
      },
      'loading -> loaded': {
      on: EVENT.LOAD_SUCCESS
      },
      'loading -> failed': {
      on: EVENT.LOAD_ERROR
      }
      }),

      onTransitions: () => ({
      'loading -> failed': () => {
      console.log('Oops...')
      }
      })
      }
      )

      return (
      <button
      className={state}
      onClick={bot.Emit(EVENT.START_LOADING)}
      disabled={bot.inState('loading')}
      >
      {bot.inState('idle', 'Load')}
      {bot.inState('loading', 'Please wait...')}
      {bot.inState('loaded', 'Done!')} ({state})
      </button>
      )
      }