Created
July 12, 2018 07:15
-
-
Save selbekk/5b9dd8a3737599dceb681ec081f12a1c to your computer and use it in GitHub Desktop.
An API state machine HOC
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
// @flow | |
import * as React from 'react'; | |
const states = { | |
IDLE: 'idle', | |
PENDING: 'pending', | |
ERROR: 'error', | |
SUCCESS: 'success', | |
}; | |
type State = { | |
currentState: $Values<typeof states>, | |
} | |
const withApiState = (TargetComponent: React.ComponentType<{}>): React.ComponentType<{}> => { | |
class WithApiState extends React.Component<{}, State> { | |
state = { | |
currentState: states.IDLE, | |
}; | |
stateMachine = { | |
isIdle: () => this.state.currentState === states.IDLE, | |
isPending: () => this.state.currentState === states.PENDING, | |
isSuccess: () => this.state.currentState === states.SUCCESS, | |
isError: () => this.state.currentState === states.ERROR, | |
setIdle: () => this.setState({ currentState: states.IDLE }), | |
setPending: () => this.setState({ currentState: states.PENDING }), | |
setSuccess: () => this.setState({ currentState: states.SUCCESS }), | |
setError: () => this.setState({ currentState: states.ERROR }), | |
}; | |
render() { | |
return ( | |
<TargetComponent {...this.props} apiState={this.stateMachine} /> | |
); | |
} | |
} | |
const targetName = TargetComponent.displayName || TargetComponent.name; | |
WithApiState.displayName = `withApiState(${targetName})`; | |
return WithApiState; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment