Skip to content

Instantly share code, notes, and snippets.

@ShMcK
Created July 17, 2018 02:50
Show Gist options
  • Save ShMcK/9ae1403f99a83b3b3f70c2427e24daf3 to your computer and use it in GitHub Desktop.
Save ShMcK/9ae1403f99a83b3b3f70c2427e24daf3 to your computer and use it in GitHub Desktop.
State Machine with external actions
type Props = {
load(): void,
}
type States = {
mode: 'loading' | 'loaded' | 'errors',
data: any,
}
const actions = {
loading() {
return { mode: 'loading', data: {} })
},
loaded(data) {
return { mode: 'loaded', data }
},
error(error) {
return { mode: 'error', data: error }
}
}
class DataLoader extends React.Component<{}, State> {
state = actions.loading()
componentDidMount() {
this.props.load()
.then(({ data, error }) => {
if (error) {
this.setState(actions.loaded(data))
} else {
this.setState(actions.error(error))
}
})
}
render() {
const { mode, data } = this.state
switch(mode) {
case 'loading':
return <Loading />
case 'loaded':
return <Loaded data={data} />
default:
return <Error data={data} />
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment