clado
TypeScript icon, indicating that this package has built-in type declarations

0.1.7 • Public • Published

Clado

git last tag npm last version

A React state machine based on Context API.


Usage:

StateMachine

The main component of clado is the StateMachine, where you can pass a bunch of components in the states using the state name as a key.

import { StateMachine } from 'clado';

const App = () => {
  return (
    <main>
      <h1>React State Machine</h1>
      <StateMachine
        initialState="a"
        states={{
          a: () => <ComponentA />,
          b: () => <ComponentB />,
        }}
      />
    </main>
  );
};

setState

To change the current state you can use the setState function of the StateMachineContext.

import { useStateMachine } from 'clado';

const ComponentA = () => {
  const { setState } = useStateMachine();

  return (
    <>
      <h2>Component A</h2>
      <button onClick={() => setState('b')}>Go To B</button>
    </>
  );
};

Data Management

Initial Data

The StateMachine accepts a data object to share data between the states.

import { StateMachine } from 'clado';

const App = () => {
  return (
    <main>
      <h1>React State Machine</h1>
      <StateMachine
        data={{
          textValue: 'a example text',
        }}
        initialState="a"
        states={{
          a: () => <ComponentA />,
          b: () => <ComponentB />,
        }}
      />
    </main>
  );
};

Update Data

The way to update this data is using the setState function of the StateMachineContext. It only overrides the passed fields, any other will be preserved.

const { setState } = useStateMachine();

<button
  onClick={() =>
    setState('b', {
      textValue: 'new text value',
    })
  }
>
  Go To B
</button>;

Reading Data

Is possible to access this data using the data returned of the StateMachineContext.

const { data } = useStateMachine<{ textValue: string }>();

<h2>{data.textValue}</h2>;

Or in the states declaration as a parameter in the function.

<StateMachine
  data={{
    textValue: 'a example text',
  } as <{ textValue: string }>}
  states={{
    a: (data) => <ComponentA text={data.textValue} />,
    b: (data) => <ComponentB text={data.textValue} />,
  }}
/>

Package Sidebar

Install

npm i clado

Weekly Downloads

5

Version

0.1.7

License

MIT

Unpacked Size

181 kB

Total Files

20

Last publish

Collaborators

  • komutilo