Skip to content

Instantly share code, notes, and snippets.

@selbekk
Created July 23, 2018 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save selbekk/909b3946fa0eff490ed9879ad21a4065 to your computer and use it in GitHub Desktop.
Save selbekk/909b3946fa0eff490ed9879ad21a4065 to your computer and use it in GitHub Desktop.
API state machine part 2
const withApiState = TargetComponent => class extends React.Component {
state = {
current: 'idle',
};
next = (input) => {
let nextState;
switch (this.state.current) {
case 'idle': nextState = 'pending'; break;
case 'pending': nextState = input ? 'success' : 'error'; break;
default: nextState = 'idle';
}
this.setState({ current: nextState });
}
render() {
return (
<TargetComponent
{...this.props}
apiState={{ ...this.state, next: this.next }}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment