Skip to content

Instantly share code, notes, and snippets.

@MicheleBertoli
Last active August 30, 2018 13:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MicheleBertoli/b8793b4047003f54964ee4442926da0d to your computer and use it in GitHub Desktop.
Save MicheleBertoli/b8793b4047003f54964ee4442926da0d to your computer and use it in GitHub Desktop.
React Automata
import React from 'react'
import { Action, withStatechart } from 'react-automata'
const statechart = {
initial: 'idle',
states: {
idle: {
on: {
FETCH: 'fetching',
},
},
fetching: {
on: {
SUCCESS: 'success',
ERROR: 'error',
},
onEntry: 'onEnterFetching',
},
success: {
onEntry: 'onEnterSuccess',
},
error: {
on: {
FETCH: 'fetching',
},
onEntry: 'onEnterError',
},
},
}
class App extends React.Component {
onEnterFetching() {
fetch('https://api.github.com/users/gaearon/gists')
.then(response => response.json())
.then(gists => this.props.transition('SUCCESS', { gists }))
.catch(() => this.props.transition('ERROR'))
}
handleClick = () => {
this.props.transition('FETCH')
}
render() {
return (
<div>
<h1>React Automata</h1>
<Action initial hide="onEnterFetching">
<button onClick={this.handleClick}>Fetch</button>
</Action>
<Action show="onEnterFetching">Loading...</Action>
<Action show="onEnterSuccess">
<ul>
{this.props.gists
.filter(gist => gist.description)
.map(gist => <li key={gist.id}>{gist.description}</li>)}
</ul>
</Action>
<Action show="onEnterError">
<button onClick={this.handleClick}>Retry</button>
Oh, snap!
</Action>
</div>
)
}
}
const options = {
devTools: true,
initialData: { gists: [] },
}
export default withStatechart(statechart, options)(App)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment