Last active
August 30, 2018 13:12
-
-
Save MicheleBertoli/b8793b4047003f54964ee4442926da0d to your computer and use it in GitHub Desktop.
React Automata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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