@fsmify/react
TypeScript icon, indicating that this package has built-in type declarations

0.0.27 • Public • Published

@fsmify/react

A react hook for interacting with fsmify's FSM.

Install

This package has a peer dependency on fsmify. So you would need to install both.

npm install fsmify @fsmify/react
// or
yarn add fsmify @fsmify/react

Example

You can see the following example live at codesandbox.

import { useFSM } from '@fsmify/react';
import { useEffect } from 'react';

export default () => {
  const fsm = useFSM({
    initialState: 'init',
    states: {
      init: { LOAD: 'loading' },
      loading: { LOAD_FINISH: 'loaded' },
      loaded: {},
    },
  });

  const load = async () => {
    fsm.send('LOAD');
    await loadData();
    fsm.send('LOAD_FINISH');
  };

  useEffect(() => {
    fsm.onBeforeEnterState('loading', () => {
      console.log('loading...');
    });
  });

  return (
    <>
      <h2>@fsmify/react demo</h2>
      {{
        init: () => <button onClick={load}>Click me to load</button>,
        loading: () => <div>Loading...</div>,
        loaded: () => <div>Hello world!</div>,
      }[fsm.currentState]()}
    </>
  );
};

API

useFSM(config: FSMConfig): ReactFSM

This method creates a ReactFSM that automatically destroy before the component unmounts. This method assumes execution to happen within a component.

See also: FSMConfig.

ReactFSM (type)

ReactFSM<State extends string, Event extends string> has most of the properties from FSM with a few tweaks:

  • currentState: State
    • the current state of fsm.
  • $fsm
    • The internal FSM. You should rarely need this.
  • getCurrentState()
    • This is removed in favor of currentState (see above).
  • destroy()
    • destroy() is removed because ReactFSM is automatically destroyed as the component unmounts.

Author

Jason Yu (@ycmjason)

Package Sidebar

Install

npm i @fsmify/react

Weekly Downloads

2

Version

0.0.27

License

MIT

Unpacked Size

7.29 kB

Total Files

6

Last publish

Collaborators

  • ycm.jason