Created
July 17, 2018 02:50
-
-
Save ShMcK/9ae1403f99a83b3b3f70c2427e24daf3 to your computer and use it in GitHub Desktop.
State Machine with external actions
This file contains hidden or 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
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