- Notifications
You must be signed in to change notification settings - Fork46
A state machine abstraction for React
License
MicheleBertoli/react-automata
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A state machine abstraction for React that provides declarative state management and automatic test generation.
reactandreact-test-rendererare peer dependencies.
yarn add react-automata
// App.jsimportReactfrom'react'import{Action,withStateMachine}from'react-automata'conststatechart={initial:'a',states:{a:{on:{NEXT:'b',},onEntry:'sayHello',},b:{on:{NEXT:'a',},onEntry:'sayCiao',},},}classAppextendsReact.Component{handleClick=()=>{this.props.transition('NEXT')}render(){return(<div><buttononClick={this.handleClick}>NEXT</button><Actionis="sayHello">Hello, A</Action><Actionis="sayCiao">Ciao, B</Action></div>)}}exportdefaultwithStateMachine(statechart)(App)
// App.spec.jsimport{testStateMachine}from'react-automata'importAppfrom'./App'test('it works',()=>{testStateMachine(App)})
// App.spec.js.snapexports[`it works: a 1`]=`<div> <button onClick={[Function]} > NEXT </button> Hello, A</div>`;exports[`it works: b 1`]=`<div> <button onClick={[Function]} > NEXT </button> Ciao, B</div>`;
ThewithStateMachine higher-order component accepts anxstate configuration object or anxstate machine, someoptions and a component.It returns a new component with specialprops,action and activity methods and additionallifecycle hooks.The initial machine state and the initial data can be passed to the resulting component through theinitialMachineState andinitialData props.
| Option | Type | Description |
|---|---|---|
| channel | string | The key of the context on which to set the state. |
| devTools | bool | To connect the state machine to theRedux DevTools Extension. |
The method to change the state of the state machine.It takes an optional updater function that receives the previous data and returns a data change.The updater can also be an object, which gets merged into the current data.
handleClick=()=>{this.props.transition('FETCH')}
The current state of the state machine.
It's not recommended to use this value because it couples the component and the state machine.
<buttononClick={this.handleClick}>{this.props.machineState==='idle' ?'Fetch' :'Retry'}</button>
All the component's methods whose names match the names of actions and activities, are fired when the related transition happen.Actions receive the state and the event as arguments. Activities receive a boolean that is true when the activity should start, and false otherwise.
For example:
conststatechart={// ...fetching:{on:{SUCCESS:'success',ERROR:'error',},onEntry:'fetchGists',},// ...}classAppextendsReact.Component{// ...fetchGists(){fetch('https://api.github.com/users/gaearon/gists').then(response=>response.json()).then(gists=>this.props.transition('SUCCESS',{ gists})).catch(()=>this.props.transition('ERROR'))}// ...}
The lifecycle method invoked when thetransition function has been called.It provides the event, and can be used to run side-effects.
componentWillTransition(event){if(event==='FETCH'){fetch('https://api.github.com/users/gaearon/gists').then(response=>response.json()).then(gists=>this.props.transition('SUCCESS',{ gists})).catch(()=>this.props.transition('ERROR'))}}
The lifecycle method invoked when a transition has happened and the state is updated.It provides the previous state machine, and the event.The currentmachineState is available inthis.props.
componentDidTransition(prevMachineState,event){Logger.log(event)}
The component to define which parts of the tree should be rendered for a given action (or set of actions).
| Prop | Type | Description |
|---|---|---|
| is | oneOfType(string, arrayOf(string)) | The action(s) for which the children should be shown. It accepts the exact value, a glob expression or an array of values/expressions (e.g.is="fetch",is="show*" oris={['fetch', 'show*']). |
| channel | string | The key of the context from where to read the state. |
| children | node | The children to be rendered when the conditions match. |
| render | func | Therender prop receives a bool (true when the conditions match) and it takes precedence over children. |
| onHide | func | The function invoked when the component becomes invisible. |
| onShow | func | The function invoked when the component becomes visible. |
<Actionis="showError">Oh, snap!</Action>
<Actionis="showError"render={visible=>(visible ?<div>Oh, snap!</div> :null)}/>
The component to define which parts of the tree should be rendered for a given state (or set of states).
| Prop | Type | Description |
|---|---|---|
| is | oneOfType(string, arrayOf(string)) | The state(s) for which the children should be shown. It accepts the exact value, a glob expression or an array of values/expressions (e.g.is="idle",is="error.*" oris={['idle', 'error.*']). |
| channel | string | The key of the context from where to read the state. |
| children | node | The children to be rendered when the conditions match. |
| render | func | Therender prop receives a bool (true when the conditions match) and it takes precedence over children. |
| onHide | func | The function invoked when the component becomes invisible. |
| onShow | func | The function invoked when the component becomes visible. |
<Stateis="error">Oh, snap!</State>
<Stateis="error"render={visible=>(visible ?<div>Oh, snap!</div> :null)}/>
The method to automagically generate tests given a component wrapped intowithStateMachine.It accepts an additionalfixtures option to describe the data to be injected into the component for a given transition, and anextendedState option to control the statechart's conditions - both are optional.
constfixtures={initialData:{gists:[],},fetching:{SUCCESS:{gists:[{id:'ID1',description:'GIST1',},{id:'ID2',description:'GIST2',},],},},}test('it works',()=>{testStateMachine(App,{ fixtures})})
You might find the answer to your questionhere.
The upgrade process is documentedhere.
Federico, for telling me "Hey, I think building UIs using state machines is the future".
David, for giving an awesometalk about infinitely better UIs, and buildingxstate.
Ryan, forexperimenting with xstate and React - Ryan's approach to React has always been a source of inspiration to me.
Erik, for writing aboutstatecharts, and showing me how to keep UI and state machine decoupled.
About
A state machine abstraction for React
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors15
Uh oh!
There was an error while loading.Please reload this page.