useTinyStateMachine
A tiny (~700 bytes) react hook to help you write finite state machines
Read the documentation for more information
Install
Import
yarn add use-tiny-state-machine
Examples
Manual traffic lights
; const stateChart = id: 'traffixLight' initial: 'green' states: green: on: NEXT: 'red' orange: on: NEXT: 'green' red: on: NEXT: 'orange' ; { const cata state dispatch = ; return <Fragment> <div className="trafficLight" style= backgroundColor: > The light is state </div> <button onClick= >Next light</button> </Fragment> ;};
Automated traffic lights with onEntry action
onEntry
is called every time you enter a given state. onEntry
is called with the current state machine instance.
; const stateChart = id: "traffixLight" initial: "green" states: green: onEntry: waitForNextLight on: NEXT: "red" orange: onEntry: waitForNextLight on: NEXT: "green" red: onEntry: waitForNextLight on: NEXT: "orange" ; { const timer = ; return ;} { const cata state dispatch = ; return <Fragment> <div style= width: "30px" height: "30px" backgroundColor: > The light is state </div> <button onClick= >Force next light</button> </Fragment> ;}
Fetching data
You can use context to store any data associated with a state.
const stateChart = id: 'userData' initial: 'idle' context: data: null error: null states: idle: on: FETCH: target: 'pending' { ; } pending: on: SUCCESS: target: 'success' FAILURE: target: 'failure' ; const UserData = { const context dispatch cata = ; return <div> </div> ;};