Created
July 23, 2018 21:16
-
-
Save selbekk/909b3946fa0eff490ed9879ad21a4065 to your computer and use it in GitHub Desktop.
API state machine part 2
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
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